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();
   // ...
});
# Java  Map 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×