Last Updated : 11 Jul, 2025
The keySet() method of the Java HashMap class is used to return a set containing all the keys in the map. This set is backed by the HashMap, so if we make any changes to the HashMap, it will be reflected in the Set as well.
Example 1: The below Java program demonstrates creating a HashMap, adding key-value pairs, displaying its contents, and retrieving the set view of keys using the keySet() method.
Java
// Java program to demonstrate the working of keySet()
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<Integer, String> m = new HashMap<>();
// Adding key-value pairs
m.put(1, "Geeks");
m.put(2, "For");
m.put(3, "Geeks");
m.put(4, "Welcomes");
m.put(5, "You");
// Displaying the HashMap
System.out.println("Initial Mappings: " + m);
// Using keySet() to get the set view of keys
System.out.println("The keys are: " + m.keySet());
}
}
Initial Mappings: {1=Geeks, 2=For, 3=Geeks, 4=Welcomes, 5=You} The keys are: [1, 2, 3, 4, 5]Syntax of keySet() Method
public Set<K> keySet()
Return Type: Return a set containing all the keys in the HashMap
Example 2: The below program demonstrates how keySet() behaves when duplicate keys are inserted into a HashMap.
Java
// Java program to demonstrate
// keySet() with duplicate keys
import java.util.HashMap;
public class Geeks {
public static void main(String[] args) {
// Creating an empty HashMap
HashMap<String, Integer> m = new HashMap<>();
// Adding key-value pairs
m.put("Geeks", 10);
m.put("for", 20);
m.put("Geeks", 30);
m.put("Welcomes", 40);
m.put("You", 50);
// Displaying the HashMap
System.out.println("Initial Mappings: " + m);
// Using keySet() to get the set view of keys
System.out.println("The keys are: " + m.keySet());
}
}
Initial Mappings: {Geeks=30, for=20, You=50, Welcomes=40} The keys are: [Geeks, for, You, Welcomes]
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