Easy Tutorial
❮ Java Generics Dir Root ❯

Java HashMap keySet() Method

Java HashMap

The keySet() method returns a Set view of all the keys contained in the map.

The syntax for the keySet() method is:

hashmap.keySet()

Note: hashmap is an object of the HashMap class.

Parameter Description:

Return Value

Returns a Set view of all the keys contained in the map.

Example

The following example demonstrates the use of the keySet() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Return a Set view of all the keys
        System.out.println("Keys: " + sites.keySet());
    }
}

Executing the above program outputs:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Keys: [1, 2, 3]

The keySet() method can be used with a for-each loop to iterate over all the keys in the HashMap.

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Return a Set view of all the keys
        System.out.println("Keys: " + sites.keySet());
        // keySet() returns a Set view of all the keys
        // for-each loop accesses each key in the view
        for(int key: sites.keySet()) {
            // Print each key
            System.out.print(key + ", ");
        }
    }
}

Executing the above program outputs:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Keys: [1, 2, 3]
1, 2, 3,

Java HashMap

❮ Java Generics Dir Root ❯