Explanation of entrySet() and four ways to iterate over a map

The entrySet() method is a method in the Map interface that returns a Set collection containing Map.Entry objects, where each Map.Entry object represents a key-value pair.

The Map.Entry interface is an internal interface that defines the methods getKey() and getValue() for retrieving the key and value, respectively.

Using the entrySet() method makes it easy to iterate through the key-value pairs in a Map collection.

Here are four common ways to iterate over a Map collection:

  1. Iterating using an Iterator:
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

// 使用entrySet()获取键值对的Set集合
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

// 使用Iterator遍历entrySet集合
Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
while(iterator.hasNext()){
   Map.Entry<String, Integer> entry = iterator.next();
   String key = entry.getKey();
   Integer value = entry.getValue();
   // do something with key and value
}
  1. Traverse using an enhanced for loop:
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

// 使用entrySet()获取键值对的Set集合
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

// 使用增强for循环遍历entrySet集合
for(Map.Entry<String, Integer> entry : entrySet){
   String key = entry.getKey();
   Integer value = entry.getValue();
   // do something with key and value
}
  1. Traverse using Lambda expressions.
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

// 使用entrySet()获取键值对的Set集合
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

// 使用Lambda表达式遍历entrySet集合
entrySet.forEach((entry) -> {
   String key = entry.getKey();
   Integer value = entry.getValue();
   // do something with key and value
});
  1. Traverse using Stream API.
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

// 使用entrySet()获取键值对的Set集合
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

// 使用Stream API遍历entrySet集合
entrySet.stream().forEach((entry) -> {
   String key = entry.getKey();
   Integer value = entry.getValue();
   // do something with key and value
});

You can use any of these four methods to iterate through the key-value pairs in a Map collection. Simply choose the appropriate method based on your specific situation.

bannerAds