如何将字符串转换为具有逗号分隔列表值的映射?

我有一个格式为“[21:[1,2,3],22:[1,2,3]]”的字符串。我该如何将其转换为以列表作为值的键值映射?



长风秋雁
浏览 107回答 3
3回答

桃花长相依

去掉开头和结尾的[和]。21:[1,2,3],22:[1,2,3]2.对]进行字符串分割,对于每个元素,字符串再次拆分为:[。第一个元素是您的 Map 键 第二个元素(逗号分隔)可以使用数组转换转换为列表

慕标5832272

一些直接的常规:String s = "[21:[1,2,3],22:[1,2,3],23:[6:[1,2],7:[3,4]]]"Map res = Eval.me sassert [1,2,3] == res[22]assert [3,4] == res[23][7]

炎炎设计

删除方括号(&nbsp;[&nbsp;)&nbsp;removeAll("\\[","")删除最后一个方括号 (&nbsp;]&nbsp;,") 以及结尾的逗号 (&nbsp;,&nbsp;) 并替换为全冒号 (&nbsp;:&nbsp;)removeAll("\\[",":")替换字符串末尾的双方括号removeAll("\\]]","")使用分割剩余的字符串split(":")然后循环String x =&nbsp; "[21:[1,2,3],22:[1,2,3]]";final HashMap<String,List<String>> test = new HashMap<>();final String s = x.replaceAll("\\[", "").replaceAll("\\],", ":").&nbsp; &nbsp; &nbsp; &nbsp; replaceAll("\\]]", "");&nbsp;final String[] split = s.split(":");for(int i =0;i<split.length;i++)&nbsp; &nbsp; test.put(split[i],Arrays.asList(split[++i]));test.forEach((k,v)-> System.out.println(k +" " +v))结果
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java