Last Updated : 06 Aug, 2025
The entrySet() method of the HashMap class in Java is used to create a set view of the mappings contained in the HashMap. This method allows us to iterate over the key-value pairs in the map or convert them into a set.
Example 1: Here, we will use the entrySet() method to view the mappings in a HashMap.
Java
// Java Program to demonstrate the entrySet() method
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<Integer, String> hm = new HashMap<>();
// Mapping string values to integer keys
hm.put(10, "Geeks");
hm.put(15, "for");
hm.put(20, "Geeks");
hm.put(25, "Welcomes");
hm.put(30, "You");
// Displaying the HashMap
System.out.println("Initial Mappings: " + hm);
// Using entrySet() to get the set view
System.out.println("The set is: " + hm.entrySet());
}
}
Initial Mappings: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=for} The set is: [20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=for]
Explanation: In the above example, the entrySet() method provides a Set view of the mappings in the HashMap. Each element in the set is a Map.Entry object that represents a key-value pair.
Syntax of HashMap entrySet() Methodpublic Set<Map.Entry<K, V>> entrySet()
Example 2: Here, we will use the entrySet() method with a HashMap having String keys and Integer values.
Java
// Using entrySet() method with a HashMap
// having String keys and Integer values
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<String, Integer> hm = new HashMap<>();
// Mapping integer values to string keys
hm.put("Geeks", 10);
hm.put("for", 15);
hm.put("Geeks", 20); // Overwriting the value for key "Geeks"
hm.put("Welcomes", 25);
hm.put("You", 30);
// Displaying the HashMap
System.out.println("Initial Mappings: " + hm);
// Using entrySet() to get the set view
System.out.println("The set is: " + hm.entrySet());
}
}
Initial Mappings: {Geeks=20, for=15, You=30, Welcomes=25} The set is: [Geeks=20, for=15, You=30, Welcomes=25]
Explanation: In the above example, the key "Geeks" is updated with the latest value 20. The entrySet() method displays all key-value pairs as a Set.
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4