简体   繁体   中英

Iterate through nested hashmap

How would I go about iterating through a nested HashMap?

The HashMap is setup like this:

HashMap<String, HashMap<String, Student>>

Where Student is an object containing a variable name . If for instance my HashMap looked like this (the following is not my code, it's just to simulate what the contents of the hashmap could be)

 hm => HashMap<'S', Hashmap<'Sam', SamStudent>>
       HashMap<'S', Hashmap<'Seb', SebStudent>>
       HashMap<'T', Hashmap<'Thomas', ThomasStudent>>

How could I iterate through all of the single letter keys, then each full name key, then pull out the name of the student?

for (Map.Entry<String, HashMap<String, Student>> letterEntry : students.entrySet()) {
    String letter = letterEntry.getKey();
    // ...
    for (Map.Entry<String, Student> nameEntry : letterEntry.getValue().entrySet()) {
        String name = nameEntry.getKey();
        Student student = nameEntry.getValue();
        // ...
    }
}

...and the var keyword in Java 10 can remove the generics verbosity:

for (var letterEntry : students.entrySet()) {
    String letter = letterEntry.getKey();
    // ...
    for (var nameEntry : letterEntry.getValue().entrySet()) {
        String name = nameEntry.getKey();
        Student student = nameEntry.getValue();
        // ...
    }
}

Java 8 lambdas and Map.forEach make bkail's answer more concise:

outerMap.forEach((letter, nestedMap) -> {
    //...
    nestedMap.forEach((name, student) -> {
        //...
    });
    //...
});

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