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?
3 Answers
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}
2 Comments
Ashley
Thanks for the clear solution. The Map should be of type <String,Integer> or <String,Object> and it shouldn't throw Exception. Right ?
ninja.coder
@Ashley I have changed the map from
<String, String> to <String, Integer> in the code. It can throw NumberFormatException if it is unable to parse the input. Please check the updated solution.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.
Comments
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)));
}
{A=1,B=2,C=3}?