java map嵌套遍历
时间: 2023-10-13 16:23:30 浏览: 149
如果嵌套的Map的层数比较少,可以使用多重循环来实现遍历。如果嵌套的层数比较多,可以使用递归来实现遍历。
以下是使用多重循环实现遍历的示例代码:
```
Map<String, Map<String, String>> map = new HashMap<>();
map.put("key1", new HashMap<>());
map.get("key1").put("subkey1", "value1");
map.get("key1").put("subkey2", "value2");
map.put("key2", new HashMap<>());
map.get("key2").put("subkey1", "value3");
map.get("key2").put("subkey2", "value4");
for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) {
String key = entry.getKey();
Map<String, String> submap = entry.getValue();
for (Map.Entry<String, String> subentry : submap.entrySet()) {
String subkey = subentry.getKey();
String value = subentry.getValue();
System.out.println("key: " + key + ", subkey: " + subkey + ", value: " + value);
}
}
```
以下是使用递归实现遍历的示例代码:
```
Map<String, Object> map = new HashMap<>();
map.put("key1", new HashMap<>());
((Map<String, Object>) map.get("key1")).put("subkey1", "value1");
((Map<String, Object>) map.get("key1")).put("subkey2", "value2");
map.put("key2", new HashMap<>());
((Map<String, Object>) map.get("key2")).put("subkey1", "value3");
((Map<String, Object>) map.get("key2")).put("subkey2", "value4");
public void traverse(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
traverse((Map<String, Object>) value);
} else {
System.out.println("key: " + key + ", value: " + value);
}
}
}
traverse(map);
```
阅读全文