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
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
HashMapwith the namemapand added three entries to the map. -
Added the entries, then got the keys of the
HashMapwith thekeySetmethod and stored them in thekeysvariable. -
Then, we added a new
4 - "four"entry to themap. -
For the newly added entry, the
key - 4was automatically available in thekeysvariable without the need to call thekeySetmethod. -
Then, we deleted the
1 - "one"entry of themap. -
The deleted entry’s
keywill not be present in thekeysvariable.