Java HashMap.keySet()

In this tutorial, we will learn about the Java HashMap.keySet() function, and learn how to use this function to get the keys of this HashMap as a Set, with the help of examples.

keySet()

HashMap.keySet() Returns a Set view of the keys contained in this map.

The syntax of keySet() function is

keySet()

Returns

The function returns Set<K>.

ADVERTISEMENT

Examples

1. keySet() basic example

In this example, we will initialize a HashMap hashMap with four mappings in it. To get the set of keys, call keySet() method on this HashMap.

Java Program

import java.util.HashMap;
import java.util.Set;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = new HashMap<>();
		hashMap.put(1, "A");
		hashMap.put(2, "B");
		hashMap.put(3, "C");
		hashMap.put(4, "D");
		System.out.println("HashMap     : " + hashMap);
		
		Set<Integer> keys = hashMap.keySet();
		System.out.println("Set of Keys : " + keys);
	}
}

Output

HashMap     : {1=A, 2=B, 3=C, 4=D}
Set of Keys : [1, 2, 3, 4]

2. keySet() – When HashMap is null

In this example, we will initialize a HashMap hashMap with null value. keySet() method throws java.lang.NullPointerException when called on a null HashMap.

Java Program

import java.util.HashMap;
import java.util.Set;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = null;
		
		Set<Integer> keys = hashMap.keySet();
		System.out.println("Set of Keys : " + keys);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at Example.main(Example.java:8)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashMap.keySet() function, and also learnt how to use this function with the help of examples.