User Brian
Brian
Level 41

How to use entrySet() method in Java

Published in the Java Developer group

What is the entrySet() method in Java?

The java.util.HashMap.entrySet() method in Java is provided by the HashMap class. It is used to return a ‘set’ of the same elements present in the HashMap.

Method Header


public Set<Map.Entry<key, value>> entrySet()

Parameters

The method does not take any parameters.

Return Type

The java.util.HashMap.entrySet() method returns an instance of class set.

Example


import java.util.HashMap;

public class Driver1 {

	public static void main(String[] args) {

		// declare a custom hash map
		HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

		// add data to the hash map
		hashMap.put(1, "Monday");
		hashMap.put(2, "Tuesday");
		hashMap.put(3, "Wednesday");
		hashMap.put(4, "Thursday");
		hashMap.put(5, "Friday");
		hashMap.put(6, "Saturday");
		hashMap.put(7, "Sunday");

		// print the original hash map
		System.out.println("Original HashMap: " + hashMap + '\n');
		// print the entrySet of the hash map
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

		// Try adding null value in the hash map
		hashMap.put(0, null);
		System.out.println("hashMap.put(0, null)");
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

		// Try adding null key and value pair to the hash map
		hashMap.put(null, null);
		System.out.println("hashMap.put(null, null)");
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

		// Try adding a null character as a value in the hash map 
		hashMap.put(null, "\0");
		System.out.println("hashMap.put(null, \"\\0\")");
		System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');

	}
}

Output

Original HashMap: {1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday} HashMap.entrySet(): [1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday] hashMap.put(0, null) HashMap.entrySet(): [0=null, 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday] hashMap.put(null, null) HashMap.entrySet(): [0=null, null=null, 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday] hashMap.put(null, "\0") HashMap.entrySet(): [0=null, null= , 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday]

Conclusion

This was a simple implementation of the Java HashMap entrySet() method. Hope you are familiar with the use of the method after going through this post. As always, you’re encouraged to practise over and over for getting good at it. Till then, keep practising and keep growing!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION