Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through nested hashmap

Tags:

java

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?

like image 761
jsan Avatar asked Oct 04 '14 00:10

jsan


People also ask

How do I access nested HashMap?

You can do it like you assumed. But your HashMap has to be templated: Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); Otherwise you have to do a cast to Map after you retrieve the second map from the first.

What is nested HashMap?

Nested HashMap is map inside another map. Its means if value of an HashMap is another HashMap.

Can you put a HashMap inside a HashMap?

Flatten a Nested HashMapOne alternative to a nested HashMap is to use combined keys. A combined key usually concatenates the two keys from the nested structure with a dot in between. For example, the combined key would be Donut.


2 Answers

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();
        // ...
    }
}
like image 68
Brett Kail Avatar answered Sep 28 '22 23:09

Brett Kail


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

outerMap.forEach((letter, nestedMap) -> {
    //...
    nestedMap.forEach((name, student) -> {
        //...
    });
    //...
});
like image 23
Jeffrey Bosboom Avatar answered Sep 29 '22 01:09

Jeffrey Bosboom