2

How do I go about splitting the following string using Java?

{525={174=2, 133=1, 182=1}}

There can be multiple lines similar to above. Each of them is a combination for the outer HashMap. Assuming there is another line

{500={100=2, 150=1, 200=1}}

The desired structure would be

525 -> 174 -> 2
       133 -> 1
       182 -> 1
500 -> 100 -> 2
       150 -> 1
       200 -> 1

I want to have the numbers in a Hashmap>.

Here is what I tried:

String s="{525={174=2, 133=1, 182=1}}";
HashMap<Integer, HashMap<Integer, Integer>> fullMap = new HashMap<Integer, HashMap<Integer, Integer>>();
Integer key, innerKey, innerValue;
key = Integer.parseInt(s.split("=")[0].replace("{",""));

I'm new to Java and don't know how to proceed further.

7
  • Can you show the keys and values you'd expect in the HashMap for the input "{525={174=2, 133=1, 182=1}}"? Commented Oct 5, 2013 at 0:32
  • 525 would be the key for the fullMap, 174, 133, 182 would be the keys for the inner map and 2,1,1 would be the values for those respectively. There can be more strings like the one above. Those would be the other keys and values of fullMap. Commented Oct 5, 2013 at 0:34
  • 1
    Please provide the syntax for the input string, and an explanation of how you want it to be split. A single example is not a proper requirements specification. Commented Oct 5, 2013 at 0:35
  • Is this always going to be for list(s) within a list (i.e. no more than two lists deep)? Or could it be deeper? If so, you're going to have to carefully count { and } (basically code a pushdown automaton). Commented Oct 5, 2013 at 0:35
  • That's kind of like JSON format, and you have nesting. It can't be reasonably represented in a "flat" Map. Commented Oct 5, 2013 at 0:37

1 Answer 1

4

try this

    String[] a = s.replaceAll("[{}]", "").split("=", 2);
    int key = Integer.parseInt(a[0].trim());
    HashMap<Integer, Integer> innerMap = new HashMap<>();
    for (String e : a[1].split(",")) {
        a = e.split("=");
        innerMap.put(Integer.parseInt(a[0].trim()),  Integer.parseInt(a[1].trim()));
    }
    fullMap.put(key, innerMap);
Sign up to request clarification or add additional context in comments.

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.