遍历嵌套的 hashmap [英] Iterate through nested hashmap
本文介绍了遍历嵌套的 hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将如何遍历嵌套的 HashMap?
How would I go about iterating through a nested HashMap?
HashMap
设置如下:
HashMap<String, HashMap<String, Student>>
其中Student
是一个包含变量name
的对象.例如,如果我的 HashMap 看起来像这样(以下不是我的代码,只是为了模拟 hashmap 的内容可能是什么)
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();
// ...
}
}
...和 Java 10 中的 var
关键字可以消除泛型冗长:
...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();
// ...
}
}
这篇关于遍历嵌套的 hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文