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()
import java.util.HashMap; class Main { public static void main(String[] args) { // create an HashMap HashMap<String, Integer> prices = new HashMap<>(); // insert entries to the HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: " + prices); // return set view of all keys System.out.println("Keys: " + prices.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
import java.util.HashMap; class Main { public static void main(String[] args) { // Creating a HashMap HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: " + numbers); // access all keys of the HashMap System.out.print("Keys: "); // keySet() returns a set view of all keys // for-each loop access each key from the view for(String key: numbers.keySet()) { // print each key System.out.print(key + ", "); } } } 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.
Also Read: