简体   繁体   中英

How to convert string into map having value as a comma separated list? [on hold]

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 ],

  1. 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

  1. Remove square bracket( [ ) removeAll("\\[","")
  2. Remove last square bracket( ] ,") together with trailing comma( , ) and replace with full-colon( : ) removeAll("\\[",":")
  3. Replace double square brackets at the end of String removeAll("\\]]","")
  4. Split the remaining String using split(":")
  5. 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))

Result在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM