What is the HashMap.keySet method in Java?

Overview

In Java, we can use the keySet method to get all the keys of the HashMap as a Set collection.

Syntax


mapObj.keySet()

Return value

The keySet method will return a set viewreturns a class object that implements the set interface, which operates on the original mapping. of all keys in the map.

Code

import java.util.HashMap;
import java.util.Set;
class Main {
public static void main( String args[] ) {
HashMap<Integer, String> map = new HashMap();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
System.out.println("The map is - " + map );
Set<Integer> keys = map.keySet();
System.out.println("The keys are - " + keys );
System.out.println("\nAdding a new entry 4 - four to the map" );
map.put(4, "four");
System.out.println("After adding the keys are - " + keys );
System.out.println("\nDelting the entry 1 - one of the map" );
map.remove(1);
System.out.println("After deleting the keys are - " + keys );
}
}

Explanation

In the code above, we:

  • Created a HashMap with the name map and added three entries to the map.

  • Added the entries, then got the keys of the HashMap with the keySet method and stored them in the keys variable.

  • Then, we added a new 4 - "four" entry to the map.

  • For the newly added entry, the key - 4 was automatically available in the keys variable without the need to call the keySet method.

  • Then, we deleted the 1 - "one" entry of the map.

  • The deleted entry’s key will not be present in the keys variable.

Free Resources