How to Iterate through a HashMap in Java

There are several ways to iterate over a HashMap in Java. The best way to traverse through a HashMap is to use a for loop, foreach, and iterators. Iterating a HashMap with the stream apis in Java 8 and Java 10 simplifies the iterator code by using the lambda expression. To iterate over the HashMap, you can use the HashMap keys, HashMap values, and HashMap Entry Object.

Although a HashMap is not a Collection, it should be seen as part of the Collections framework. As a result, a Map is a different interface from the Collections interface. An iterator is a method of iterating across a collection. In the Java Collections Framework, it replaces Enumeration.

In Java, there are several ways to iterate over a Map. Let’s look over the most frequent approaches and carefully consider on their benefits and drawbacks. Because all Java maps implement the Map interface, the approaches below will work with any map implementation.



1. Using map.foreach

The map.foreach method is the best way to iterate across a HashMap. The key and values object will be provided directly by the map.foreach method. The map.foreach method has a simple and efficient syntax. The performance of the map.foreach function is excellent. The following example demonstrates how to loop through a HashMap in Java using the map.foreach method.

package com.yawintutor;

import java.util.HashMap;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		map.forEach((key, value) -> { System.out.println(key + " " + value); });
	}
}

Output

1 One
2 Two
3 Three


2. Using for keyset

The for loop can traverse through keysets in the HashMap. The keyset will be a collection of all the keys in the HashMap. The for loop iterates over the keys, going through each one. The map get api will return the value associated with the specified key. Iterating through the keyset in a for loop will return all of the HashMap’s keys and values.

package com.yawintutor;

import java.util.HashMap;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		for (String key : map.keySet()) {
			System.out.println(key + " " + map.get(key));
		}		
	}
}

Output

1 One
2 Two
3 Three


3. Using for entrySet – Java 10 onwards

In Java 10, the var data type allows you to configure a variable. The var is a generic form for storing any Java objects without giving the class name. To iterate the Hashmap, you don’t need to specify the Entry object in the for loop. The keys and values are accessed via the Entry object, which is stored in the var data type variable.

package com.yawintutor;

import java.util.HashMap;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");

		for (var entry : map.entrySet()) {
		    System.out.println(entry.getKey() + " " + entry.getValue());
		}		
	}
}

Output

1 One
2 Two
3 Three


4. Using for Map.Entry

The Map Entry object is another option for iterating across the HashMap. The for loop iterates through the HashMap EntrySet’s collection of Map Entry objects. The key value stored in the HashMap is contained in the Map Entry object. You may get the key and value associated with the key using the Map Entry object.

package com.yawintutor;

import java.util.HashMap;
import java.util.Map;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		for (Map.Entry<String, String> entry : map.entrySet()) {
		    System.out.println(entry.getKey() + " " + entry.getValue());
		}		
	}
}

Output

1 One
2 Two
3 Three


5. Using Java Stream foreach

Streaming of Java Objects is introduced in Java 8. You can iterate the Entry object using the stream of HashMap objects. The Entry object in the streams will be returned by the forEach method. The HashMap’s Entry object can be accessed using the Lambda expression.

package com.yawintutor;

import java.util.HashMap;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		map.entrySet().stream().forEach(entry -> { System.out.println(entry.getKey() + " " + entry.getValue()); });
		
	}
}

Output

1 One
2 Two
3 Three


6. Using Java Stream parallel

The java stream parallel api provides for parallel access to the object. This api will allow concurrent access to the entry object from the HashMap. The HashMap will be iterated by accessing the entry object in parallel. The foreach method iterates across the concurrently accessed entry objects.

package com.yawintutor;

import java.util.HashMap;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");

		map.entrySet().stream().parallel().forEach(entry -> { System.out.println(entry.getKey() + " " + entry.getValue()); });		
	}
}

Output

1 One
2 Two
3 Three


7. Using for iterator

The Iterator interface in Java is used to iterate across the entries in a collection object. The iterator is used to loop through the HashMap’s objects. The HashMap’s entryset object is used to generate the iterator. The for loop is used to obtain the key and value pair in the Entry Object using the HashMap iterator.

package com.yawintutor;

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

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
				
		for (Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); iterator.hasNext(); ) {
		    Map.Entry<String, String> entry = iterator.next();
		    System.out.println(entry.getKey() + " " + entry.getValue());
		}		
	}
}

Output

1 One
2 Two
3 Three


8. Using while KeySet iterator

The Hashmap is iterated over using the while loop. The HashMap’s keyset object is used to generate the iterator. The iterator will be used to iterate the keyset in the while loop.

package com.yawintutor;

import java.util.HashMap;
import java.util.Iterator;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		Iterator<String> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println(key + " " + map.get(key));
		}	
	}
}

Output

1 One
2 Two
3 Three


9. Using While Entryset Iterator

The Hashmap is iterated over using the while loop. The HashMap’s entryset object is used to generate the iterator. The iterator will be used to iterate the entryset in the while loop.

package com.yawintutor;

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

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
		    Map.Entry<String, String> entry = iterator.next();
		    System.out.println(entry.getKey() + " " + entry.getValue());
		}
	}
}

Output

1 One
2 Two
3 Three


10. Using While Values Iterator

The Hashmap is iterated over using the while loop. The HashMap’s values object is used to generate the iterator. The iterator will be used to iterate the values in the while loop.

package com.yawintutor;

import java.util.HashMap;
import java.util.Iterator;

public class JavaIterator {
	public static void main(String[] args) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("1","One");
		map.put("2", "Two");
		map.put("3", "Three");
		
		Iterator<String> iterator = map.values().iterator();
		while (iterator.hasNext()) {
			String value = iterator.next();
			System.out.println(value);
		}
	}
}

Output

One
Two
Three