2

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?

2
  • 2
    what is {A=1,B=2,C=3}? Commented Apr 9, 2016 at 10:00
  • @wero In JSON format , it is the value parameter of {key:value} pair. Example: {'IdNo.' : "{A=1, B=2, C=3}"}, IdNo. is the key and {A=1, B=2, C=3} is the value. I want to convert the value field to map so that I can access the the value of A, B and C. Commented Apr 9, 2016 at 10:04

3 Answers 3

3

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the clear solution. The Map should be of type <String,Integer> or <String,Object> and it shouldn't throw Exception. Right ?
@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.
1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.