How to parse the string into map

后端 未结 5 1147
失恋的感觉
失恋的感觉 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:12

    public class TestMapParser {
        @Test
        public void testParsing() {
            Map 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 parseMap(final String input) {
            final Map map = new HashMap();
            for (String pair : input.split("&")) {
                String[] kv = pair.split("=");
                map.put(kv[0], kv[1]);
            }
            return map;
        }
    }
    

提交回复
热议问题