java 遍历嵌套的哈希图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26188532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through nested hashmap
提问by jsan
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
. 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)
Student
包含变量的对象在哪里name
。例如,如果我的 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?
我怎么能遍历所有的单字母键,然后每个全名键,然后拉出学生的名字?
回答by Brett Kail
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();
// ...
}
}
回答by Jeffrey Bosboom
Java 8 lambdas and Map.forEach
make bkail's answermore concise:
Java 8 lambdasMap.forEach
并使bkail 的答案更简洁:
outerMap.forEach((letter, nestedMap) -> {
//...
nestedMap.forEach((name, student) -> {
//...
});
//...
});