daicy
发布于 2023-01-30 / 900 阅读
0
0

java 循环遍历 map

Java 中可以使用以下方法遍历 Map:

  1. for-each loop:

for (Map.Entry<Key, Value> entry : map.entrySet()) {
   Key key = entry.getKey();
   Value value = entry.getValue();
   // ...
} 
  1. 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();
   // ...
}
  1. Stream API:
map.forEach((key, value) -> {
   // ...
}); 
  1. Java 8 forEach + Lambda:
map.entrySet().forEach(entry -> {
   Key key = entry.getKey();
   Value value = entry.getValue();
   // ...
});

评论