I have a string in the format - "[21:[1,2,3],22:[1,2,3]]". How am I supposed to convert this into a key-value map having list as a value?
1.Remove the [ and ] at the beginning and end. 21:[1,2,3],22:[1,2,3]
2.Do a string split for ],
For each element, String split again for:[.
First element is your Map key Second element (comma separated) can be converted to list using array conversion
removeAll("\\[","")
removeAll("\\[",":")
removeAll("\\]]","")
split(":")
Then loop
String x = "[21:[1,2,3],22:[1,2,3]]"; final HashMap<String,List<String>> test = new HashMap<>(); final String s = x.replaceAll("\\[", "").replaceAll("\\],", ":"). replaceAll("\\]]", ""); final String[] split = s.split(":"); for(int i =0;i<split.length;i++) test.put(split[i],Arrays.asList(split[++i])); test.forEach((k,v)-> System.out.println(k +" " +v))
Some straight forward groovy:
String s = "[21:[1,2,3],22:[1,2,3],23:[6:[1,2],7:[3,4]]]"
Map res = Eval.me s
assert [1,2,3] == res[22]
assert [3,4] == res[23][7]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.