entrySet()" should be iterated when both the key and value are neede
时间: 2023-12-10 08:42:36 浏览: 78
详解JAVA里面获取map的key和value的方法
5星 · 资源好评率100%
The `entrySet()` method in Java returns a set view of the mappings contained in a map. Each element in the set is a `Map.Entry` object, which represents a key-value pair in the map.
When you need to iterate through a map and access both the keys and values, it is more efficient to use the `entrySet()` method instead of calling the `keySet()` method and then retrieving each value using the `get()` method. This is because calling `get()` for each key requires a separate map lookup, whereas iterating through the `entrySet()` allows you to access both the key and value in one go.
Here is an example of how to use `entrySet()` to iterate through a map and access both the keys and values:
```
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " = " + value);
}
```
This will output:
```
apple = 1
banana = 2
orange = 3
```
阅读全文