How to use the HashMap keySet() function in Java

An instance of the Java HashMap calls the keySet() function, which returns a new set containing the keys of the HashMap.

To use the keySet() function with HashMap, the program needs to import the java.util.HashMap module:

import java.util.HashMap;

Prototype

map, an instance of the Java HashMap, can call the keySet() function as illustrated below:

Parameters and return type

The keySet() function accepts no parameters and returns a set containing all the HashMap keys.

Example

The following example demonstrates how to use the keySet() function with a Java HashMap:

  • The program below creates a HashMap results and indicates in line 7 that the first element of a pair is a string and the second element is an integer.
  • It then populates the results HashMap through the put() method and displays the HashMap.
  • The program generates keys using the keySet() method and displays the keys.
import java.util.*;
class ExampleHashMap {
public static void main(String[] args) {
// create a new hashmap
HashMap<String, Integer> results = new HashMap<>();
System.out.println("A HashMap for mapping marks to students");
// add elements to the hashmap
results.put("Ali", 89);
results.put("Ahmed", 95);
results.put("Sana", 70);
results.put("Amna", 100);
//display the hashmap
System.out.println("Updated HashMap: " + results);
//generate key set using the keySet function
Set mapKeys = results.keySet();
//display the keys
System.out.println("keys: " + mapKeys);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved