How to get Keys and Values from HashMap in Java?

Example of getting keys and values from HashMap in Java using the entrySet() method of HashMap.

How to get Keys and Values from HashMap in Java?

Example of getting keys and values from HashMap in Java using the entrySet() method of HashMap.

How to get Keys and Values from HashMap in Java?

How to get Keys and Values from HashMap in Java? Example program of iterating through HashMap

In this tutorial I will explain you how you can iterate through HashMap using the entrySet() method of HashMap class. You will be able to iterate the keys and get the values and print on the console.

How to get keys and values from HashMap? This is the most asked questions in the Java interviews. There is no iterator method in the HashMap, so directly it is not possible to iterate through keys and get the values. So, let's see how to iterate through keys and get the values from a HashMap object.

The entrySet() method of HashMap

Let's discuss the entrySet() method of HashMap class which can be used to iterate through the keys.

Declaration

Following are the declaration of the method:

public Set<Map.Entry<K,V>> entrySet()

Parameters

This method is not taking any parameters.

Return Value

The entrySet() method returns a set view of the mappings objects contained in the map.

Here is the code of the program:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {
	public static void main(String[] args) {
		// Create a Empty HashMap 
		HashMap hashMap = new HashMap();
		
		// Put values in hash map
		hashMap.put("one", "1");
		hashMap.put("two", "2");
		hashMap.put("three", "3");
		hashMap.put("four", "4");
		hashMap.put("five", "5");

		//Get the set
		Set set = (Set) hashMap.entrySet();

		//Create iterator on Set 
		Iterator iterator = set.iterator();
		
		System.out.println("Display Values.");

		while (iterator.hasNext()) {
		Map.Entry mapEntry = (Map.Entry) iterator.next();
			
			// Get Key
		String keyValue = (String) mapEntry.getKey();
			
		//Get Value
		String value = (String) mapEntry.getValue();

		System.out.println("Key : " + keyValue + "= Value : " + value);
		}
	}
}

If you run the program it will show the following output:

D:\Tutorials\Examplecode>java HashMapDemo
Display Values.
Key : two= Value : 2
Key : five= Value : 5
Key : one= Value : 1
Key : three= Value : 3
Key : four= Value : 4

In this tutorial we have learned how to get the key set from a HashMap object and then iterate and print it on console.

Check Java for Beginners