简体   繁体   English

遍历嵌套的哈希图

[英]Iterate through nested hashmap

How would I go about iterating through a nested HashMap?我将如何遍历嵌套的 HashMap?

The HashMap is setup like this: HashMap设置如下:

HashMap<String, HashMap<String, Student>>

Where Student is an object containing a variable name .其中Student是一个包含变量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)例如,如果我的 HashMap 看起来像这样(以下不是我的代码,它只是为了模拟 hashmap 的内容可能是什么)

 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: ...Java 10 中的var关键字可以消除泛型的冗长:

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: Java 8 lambdas 和Map.forEach使bkail 的回答更加简洁:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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