Reputation: 491
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
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
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
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