dimas
dimas

Reputation: 2597

Getting value from Nested HashMap into another Map

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!

Upvotes: 1

Views: 3242

Answers (1)

Hunter McMillen
Hunter McMillen

Reputation: 61510

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.

Upvotes: 4

Related Questions