How to parse the string into map

后端 未结 5 1138
失恋的感觉
失恋的感觉 2021-02-15 02:24

have a string like A=B&C=D&E=F, how to parse it into map?

相关标签:
5条回答
  • 2021-02-15 03:05

    I would use split

    String text = "A=B&C=D&E=F";
    Map<String, String> map = new LinkedHashMap<String, String>();
    for(String keyValue : text.split(" *& *")) {
       String[] pairs = keyValue.split(" *= *", 2);
       map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
    }
    

    EDIT allows for padded spaces and a value with an = or no value. e.g.

    A = minus- & C=equals= & E==F
    
    0 讨论(0)
  • 2021-02-15 03:08

    just use guava Splitter

    String src="A=B&C=D&E=F";
    Map map= Splitter.on('&').withKeyValueSeparator('=').split(src);
    
    0 讨论(0)
  • 2021-02-15 03:12
    public class TestMapParser {
        @Test
        public void testParsing() {
            Map<String, String> map = parseMap("A=B&C=D&E=F");
            Assert.assertTrue("contains key", map.containsKey("A"));
            Assert.assertEquals("contains value", "B", map.get("A"));
    
            Assert.assertTrue("contains key", map.containsKey("C"));
            Assert.assertEquals("contains value", "D", map.get("C"));
    
            Assert.assertTrue("contains key", map.containsKey("E"));
            Assert.assertEquals("contains value", "F", map.get("E"));
        }
    
        private Map<String, String> parseMap(final String input) {
            final Map<String, String> map = new HashMap<String, String>();
            for (String pair : input.split("&")) {
                String[] kv = pair.split("=");
                map.put(kv[0], kv[1]);
            }
            return map;
        }
    }
    
    0 讨论(0)
  • 2021-02-15 03:22

    Split the string (either using a StringTokenizer or String.split()) on '&'. On each token just split again on '='. Use the first part as the key and the second part as the value.

    It can also be done using a regex, but the problem is really simple enough for StringTokenizer.

    0 讨论(0)
  • 2021-02-15 03:27
    String  t = A=B&C=D&E=F;
    Map map = new HashMap();
    String[] pairs = t.split("&");
    //TODO 1) Learn generis 2) Use gnerics    
    for (String pair : pairs)
    {
        String[] kv = pair.split("=");
        map.put(kv[0], kv[1]);
    }
    
    0 讨论(0)
提交回复
热议问题