The entrySet() method of the java.util.Map interface returns a set view of all key–value mappings in the map, where each element is a Map.Entry<K, V>.
- Each Map.Entry represents a single key–value pair from the map.
- It allows simultaneous access to both keys and values during iteration.
- More efficient than keySet() when values are also required, as it avoids extra get() calls.
import java.util.*;
class GFG {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
for (Map.Entry<Integer, String> e : map.entrySet()) {
System.out.println(e.getKey() + " : " + e.getValue());
}
}
}
Output
1 : Java 2 : Python
Explanation:
- entrySet() returns a set view of all key–value pairs in the map.
- Each element in the set is a Map.Entry object containing a key and its corresponding value.
- This approach allows efficient iteration when both keys and values are required.
Syntax
map.entrySet()
- Parameters: The method does not take any parameter.
- Return Value: The method returns a set having same elements as the hash map. Below programs illustrate the java.util.Map.entrySet() Method:
Note: The returned set is backed by the map, meaning changes to the map are reflected in the set and vice versa.
Example: Iterating Over a Map Using entrySet()
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
Output
1 = Java 2 = Python 3 = C++
Explanation:
- entrySet() returns a set of key–value pairs.
- Each iteration gives a Map.Entry object.
- getKey() retrieves the key, and getValue() retrieves the value.
Example: Modifying Values Using entrySet()
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 5);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
entry.setValue(entry.getValue() + 5);
}
System.out.println(map);
}
}
Output
{Apple=15, Banana=10}
Explanation:
- setValue() updates the value of the current entry.
- Since entrySet() is backed by the map, changes reflect in the original map.
entrySet() vs keySet()
entrySet() | keySet() |
|---|---|
Accesses both key and value | Accesses only keys |
More efficient for iteration | Requires extra lookup for values |
Uses Map.Entry | Uses only keys |