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;
map, an instance of the Java HashMap, can call the keySet() function as illustrated below:
The keySet() function accepts no parameters and returns a set containing all the HashMap keys.
The following example demonstrates how to use the keySet() function with a Java HashMap:
results and indicates in line 7 that the first element of a pair is a string and the second element is an integer.results HashMap through the put() method and displays the HashMap.keySet() method and displays the keys.import java.util.*;class ExampleHashMap {public static void main(String[] args) {// create a new hashmapHashMap<String, Integer> results = new HashMap<>();System.out.println("A HashMap for mapping marks to students");// add elements to the hashmapresults.put("Ali", 89);results.put("Ahmed", 95);results.put("Sana", 70);results.put("Amna", 100);//display the hashmapSystem.out.println("Updated HashMap: " + results);//generate key set using the keySet functionSet mapKeys = results.keySet();//display the keysSystem.out.println("keys: " + mapKeys);}}
Free Resources