java遍历多层map
时间: 2023-10-15 09:29:56 浏览: 190
在Java中遍历多层Map可以使用不同的方法。以下是三种常见的遍历方式:
1. 使用stream流遍历Map(JDK8不推荐写法,重复计算):
```
map.entrySet().stream().forEach((Map.Entry<Integer, Map<Integer, String>> entry) -> {
entry.getValue().entrySet().forEach(innerEntry -> {
System.out.println(innerEntry.getKey());
System.out.println(innerEntry.getValue());
});
});
```
2. 使用foreach遍历方式(JDK8以下推荐写法):
```
for (Map.Entry<Integer, Map<Integer, String>> entry : map.entrySet()) {
for (Map.Entry<Integer, String> innerEntry : entry.getValue().entrySet()) {
System.out.println(innerEntry.getKey());
System.out.println(innerEntry.getValue());
}
}
```
3. 使用Iterator的entrySet写法(推荐JDK8以下):
```
Iterator<Map.Entry<Integer, Map<Integer, String>>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Map<Integer, String>> entry = iterator.next();
Iterator<Map.Entry<Integer, String>> innerIterator = entry.getValue().entrySet().iterator();
while (innerIterator.hasNext()) {
Map.Entry<Integer, String> innerEntry = innerIterator.next();
System.out.println(innerEntry.getKey());
System.out.println(innerEntry.getValue());
}
}
```
这些方法可以根据具体情况选择使用,根据你的需求选择适合的方式来遍历多层Map。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Java遍历Map五种方法](https://blog.csdn.net/HcJsJqJSSM/article/details/109017247)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文