Java: Iterate through a HashMap which is inside another HashMap

15,696

Solution 1

You could iterate the child map similar to how you've done the parent:

Iterator<Map.Entry<String, Map<String, String>>> parent = PropertyHolder.entrySet().iterator();
while (parent.hasNext()) {
    Map.Entry<String, Map<String, String>> parentPair = parent.next();
    System.out.println("parentPair.getKey() :   " + parentPair.getKey() + " parentPair.getValue()  :  " + parentPair.getValue());

    Iterator<Map.Entry<String, String>> child = (parentPair.getValue()).entrySet().iterator();
    while (child.hasNext()) {
        Map.Entry childPair = child.next();
        System.out.println("childPair.getKey() :   " + childPair.getKey() + " childPair.getValue()  :  " + childPair.getValue());

        child.remove(); // avoids a ConcurrentModificationException
    }

}

I've presumed you want to call .remove() on the child map, which will lead to a ConcurrentModificationException if done while looping the entrySet - it looks as though you discovered this already.

I've also swapped out your use of casting with strongly-typed generics as suggested in the comments.

Solution 2

    for (Entry<String, Map<String, String>> entry : propertyHolder.entrySet()) {
        Map<String, String> childMap = entry.getValue();

        for (Entry<String, String> entry2 : childMap.entrySet()) {
            String childKey = entry2.getKey();
            String childValue = entry2.getValue();
        }
    }
Share:
15,696
Chanuka Ranaba
Author by

Chanuka Ranaba

Updated on June 25, 2022

Comments

  • Chanuka Ranaba
    Chanuka Ranaba about 2 years

    I want to iterate through a HashMap which is inside another HashMap

    Map<String, Map<String, String>> PropertyHolder
    

    I was able to iterate through the parent HashMap as following,

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

    but could not able to iterate through the child Map, It can be done by converting pair.getValue().toString() and separated using , and =. Is there any other way of iterating it?