Java HashMap keySet()

The syntax of the keySet() method is:

hashmap.keySet()

Here, hashmap is an object of the HashMap class.


keySet() Parameters

The keySet() method does not take any parameter.


keySet() Return Value

  • returns a set view of all the keys of the hashmap

Note: The set view only shows all keys of the hashmap as a set. The view does not contain actual keys. To learn more about view in Java, visit the view of a collection.


Example 1: Java HashMap keySet()

Output

HashMap: {Pant=150, Bag=300, Shoes=200}
Keys: [Pant, Bag, Shoes]

In the above example, we have created a hashmap named prices. Notice the expression,

prices.keySet()

Here, the keySet() method returns a set view of all the keys present in the hashmap.

The keySet() method can also be used with the for-each loop to iterate through each key of the hashmap.

Example 2: keySet() Method in for-each Loop

Output

HashMap: {One=1, Two=2, Three=3}
Keys: One, Two, Three,

In the above example, we have created a hashmap named numbers. Notice the line,

String key:  numbers.keySet()

Here, the keySet() method returns a set view of all the keys. The variable key access each key from the view.

Note: The Key of HashMap is of String type. Hence, we have used the String variable to access the keys.

Recommended Reading