Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
264 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
        // ...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...