The keySet() in Hashmap is used to get a set of the keys present in a hashmap.

Method signature:

The signature for keySet() is shown below:

public Set keySet()

Methods parameters and return type:

Parameter: It doesn’t take any parameters.

Return type: It returns a set of keys.

Throws: N/A.

Hashmap keySet() Example:

In this example, we have displayed a key set of a hashmap by using this method.

Source code:

public class Example1 {

    public static void main(String[] args) {

        HashMap<Integer, String> map = new HashMap<>();
        Set set = new HashSet<>();
        map.put(1, "1");
        map.put(10, "2");
        map.put(100, "3");
        map.put(1000, "4");
        map.put(10000, "5");
        System.out.println("The hashmap is: "+map);
        set = map.keySet();
        System.out.println("The key set is: "+set);
    }
}

Output:

run:
The hashmap is: {10000=5, 1=1, 100=3, 1000=4, 10=2}
The key set is: [10000, 1, 100, 1000, 10]
BUILD SUCCESSFUL (total time: 0 seconds)

Example 2:

In this example, we have used keySet() on an empty hashmap, and it returns us an empty set without generating any exception.

Source code:

public class Example2 {
    
    public static void main(String[] args) {

        HashMap<Integer, String> map = new HashMap<>();
        Set set = new HashSet<>();
        set = map.keySet();        
        System.out.println("The key set is: "+set);
    }
}

Output:

run:
The key set is: []
BUILD SUCCESSFUL (total time: 1 second)

References:

Leave A Comment