【问题标题】:Convert String to Map Ex - String str = "{Topic0 : 0, Topic1 :1, Topic2 : 0}";将字符串转换为地图 Ex - String str = "{Topic0 : 0, Topic1 :1, Topic2 : 0}";
【发布时间】:2020-06-17 07:25:21
【问题描述】:
String str = "{Topic0 : 0, Topic1 :1, Topic2 : 2}";

如何将包含、键和值的字符串转换为映射?

map.put("Topic0", 0);
map.put("Topic1", 1);
map.put("Topic2", 2);

所以我想要一个 Map,其键为“Topic0,Topic1,Topic2”,对应的值为“0,1,2”。

【问题讨论】:

    标签: java string collections


    【解决方案1】:
    public static void main(String[] strings) {
        String str = "{Topic0 : 0, Topic1 :1, Topic2 : 2}";
        //remove first and last char, i.e { and }
        str = str.substring(1, str.length()-1);
        Map<String,String> myMap = Pattern.compile("\\s*,\\s*")
                //split at ,
                .splitAsStream(str)
                //split at :
                .map(e -> e.split("\\s*:\\s*"))
                //map
                .map(e -> new AbstractMap.SimpleEntry<>(e[0],e[1]))
                //collect
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        System.out.println(myMap);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-13
      • 2019-10-29
      • 2010-09-24
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2015-09-22
      • 2018-04-02
      相关资源
      最近更新 更多