简体   繁体   中英

Converting strings to Map in java

我应该如何在Java中将{A=1,B=2,C=3}转换为地图类型对象,例如{'A':"1",'B':"2",'C':"3"} ?是否有现有的API可以执行此操作?

You can simply use split() and do something like this:

public static void main (String[] args) throws Exception {
    String input = "{A=1,B=2,C=3}";
    Map<String, Integer> map = new HashMap<>();
    for(String str : input.substring(1,input.length() - 1).split(",")) {
        String[] data = str.split("=");
        map.put(data[0],Integer.parseInt(data[1]));
    }
    System.out.println(map);
}

Output:

{A=1, B=2, C=3}

Here's a one liner:

Map<String, Integer> map = 
  Arrays.stream(str.replaceAll("^.|.$", "").split(","))
  .map(s -> s.split("="))
  .collect(Collectors.toMap(a -> a[0], a -> new Integer(a[1])));

Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)

This first trims the first and last chars, then splits on comma, then splits again on equals sign, then collects to a map. Voila.

Regular expressions are pretty good for capturing text from a well formatted string. Something like the following:

Map<String,Integer> map = new HashMap<>();
Pattern pattern = Pattern.compile("(\\w+)=(\\d+)");
Matcher matcher = pattern.matcher(input);
for (int g = 1; g < matcher.groupCount(); g += 2) {
    map.put(matcher.group(g), Integer.parseInt(matcher.group(g+1)));
}

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