Ashley
Ashley

Reputation: 491

Converting strings to Map in java

How should I convert {A=1,B=2,C=3} into map type object like {'A':"1",'B':"2",'C':"3"} in java ?Is there any existing API to do this?

Upvotes: 2

Views: 2573

Answers (3)

Bohemian
Bohemian

Reputation: 425288

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.

Upvotes: 1

ninja.coder
ninja.coder

Reputation: 9658

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}

Upvotes: 3

sprinter
sprinter

Reputation: 27986

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)));
}

Upvotes: 0

Related Questions