Java HashMap.entrySet()

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

entrySet()

HashMap.entrySet() returns a Set view of the mappings contained in this map.

The HashMap object should not be null, else, the function throws java.lang.NullPointerException.

The syntax of entrySet() function is

</>
Copy
entrySet()

Returns

The function returns Set<Map.Entry<K,V>> value.

Examples

1. HashMap entrySet() basic example

In this example, we will initialize a HashMap hashMap with mappings from String to Integer. To get Set view of this hashMap, we will call entrySet() method on this HashMap.

Java Program

</>
Copy
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

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

Output

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

2. entrySet() – When HashMap is null

In this example, we will initialize a HashMap hashMap with null. Calling HashMap.entrySet() method on null object should throw java.lang.NullPointerException.

Java Program

</>
Copy
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Example{ 
	public static void main(String[] args) {
		HashMap<String,Integer> hashMap = null;
		
		Set<Entry<String,Integer>> set = hashMap.entrySet();
		System.out.println("Set view :" + set);
	}
}

Output

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

Conclusion

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