1

Hi, I wanted to store key and value of a nested Map that looks like this:

Map<ArrayList <String>, Map<String, Integer>> NestedMap = new HashMap<ArrayList<String>, Map<String, Integer>();

into another variable let say getKeyFromInsideMap and getValueFromInsideMap. So it would be the values of the inside Map String and Integer that am interested in accessing. How do I this in a code?

I tried several examples here in the forum but I don't know how the syntax would look like. Could you please provide some code for this. Thank you!

Pendo826
  • 1,002
  • 18
  • 47
dimas
  • 2,487
  • 6
  • 40
  • 66

1 Answers1

4

You get the values from the nested by Map the same way as you get them from an unnested Map, you just have to apply the same process twice:

//Java7 Diamond Notation
Map<ArrayList, Map<String, Integer>> nestedMap = new HashMap<>();

//get nested map 
Map<String, Integer> innerMap = nestedMap.get(some_key_value_string);

//now get the Integer value from the innerMap
Integer innerMapValue = innerMap.get(some_key_value_string);

Also if you are looking for a specific key, you can iterate over the map like so:

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println("Key: " + pairs.getKey() + " Val: " + pairs.getValue()));
    it.remove(); // avoids a ConcurrentModificationException
}

this will iterate over all of the keys and value of a single map.

Hope this helps.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • Hi thank you for your quick reply. I tried your first solution the one without a while loop. When I get to the part nestedMap.get(some_key_value_string); it asks for a value. Normally i would just enter something in there but what if I wanted to get all the keys and values in the inside map? What would the loop look like? What variable will I assign to replace the some_key_value_string? – dimas May 15 '12 at 19:43
  • @dimas If you are trying to get all the keys and value of the map and not a specific one you should follow the second example. Just not that in the nestedMap `pairs.getValue()` will return a `Map` – Hunter McMillen May 15 '12 at 19:51
  • cool tnx, I was able to get it. So what you did in the Map.Entry pairs = (Map.Entry)it.next is to make pair a temporary Map that would store the key-value pair of the inside map? – dimas May 15 '12 at 20:02
  • The `Map.Entry` object stores a single key value pairing. In the case of your nestedMap `Map.Entry` contains a `String` and a `Map`, in the case of your inner map it contains a `String` and an `Integer`. – Hunter McMillen May 15 '12 at 20:04
  • ok now I understand whats happening. Thanks for all your help! – dimas May 15 '12 at 20:09