Java HashMap keySet() Method

Java HashMap Java HashMap

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

The syntax of the keySet() method is:

hashmap.keySet()

Note:hashmap is an object of the HashMap class.

Parameter Description:

  • None

Return Value

Returns a Set view of all 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<Integer, String> sites = new HashMap<>();

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

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

Executing the above program outputs:

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

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

Example

import java.util.HashMap;

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

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

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

          // Output each key
            System.out.print(key + ", ");
        }

    }
}

Executing the above program outputs:

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

Java HashMap Java HashMap

Other Extensions