Java 中可以使用以下方法遍历 Map:
- for-each loop:
for (Map.Entry<Key, Value> entry : map.entrySet()) {
Key key = entry.getKey();
Value value = entry.getValue();
// ...
}
- Iterator:
Iterator<Map.Entry<Key, Value>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Key, Value> entry = it.next();
Key key = entry.getKey();
Value value = entry.getValue();
// ...
}
- Stream API:
map.forEach((key, value) -> {
// ...
});
- Java 8 forEach + Lambda:
map.entrySet().forEach(entry -> {
Key key = entry.getKey();
Value value = entry.getValue();
// ...
});