简体   繁体   中英

Java - How to iterate over a hashmap of list of hashmap

I want to iterate over a hashmap of list of hashmap.

for example,

HashMap <String, List <HashMap<String, String> > >

How do I iterate over this map.

Please help me to find a solution.

Let us name your map.

HashMap<String, List<HashMap<String, String>>> map; //I'll assume it is initialized and filled with something.

for (String key : map.keySet()) {
    for (HashMap<String, String> map2 : map.get(key)) {
        for (String key2 : map2.keySet()) {
            //do something
        }
    }
}

Another approach is to use nested loops through collections:

for (List<HashMap<String, String>> list : map.values()) {
    for (HashMap<String, String> map2 : list) {
        for (String veryInnerValue : map2.values()) {
            //do something
        }
    }
}

The differ a bit. In case you don't need to know the key of the value, the second is better.

You should probably look over your design, this sounds like something that could be structured in an easier way. Consider maybe breaking this collection up into classes. But, in case you cannot change it now (or don't have the time), I'll offer a hand.

The easiest way is probably to break the iteration up in several steps:

  1. Iterate over the inner HashMaps
  2. Iterate over the lists
  3. Iterate over the content in the inner HashMaps

Here's the basic code:

for( List<HashMap<String, String>> list : outer.values() ) {
    for( HashMap<String, String> map : list ) {
        for( String value : map.values() ) {
            //Do something
        }
    }
}

If you need to know key and value for each map :

Map<String, List<HashMap<String, String>>> myMap = new HashMap<String, List<HashMap<String, String>>>();

// loop for first map
for (Entry<String, List<HashMap<String, String>>> myMapEntry : myMap.entrySet()) {
    System.out.println("myMap entry key" + myMapEntry.getKey() + ", key ");

    // loop for list (value of entry)
    for (HashMap<String, String> valueOfList : myMapEntry.getValue()) {

        // loop for second map                
        for (Entry<String, String> entryOfMapOfList : valueOfList.entrySet()) {
            System.out.println("key " + entryOfMapOfList.getKey() + " value " + entryOfMapOfList.getValue());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM