You can use the HashMap keys, HashMap values, and HashMap Entry Object to iterate over the HashMap in Java. The iterator will run through each element in the HashMap one by one until the HashMap is exhausted. Depending on the data structure and architecture of the collection object, the iterator can travel forward or backward. The iterator is a pointer in the HashMap that indicates the current stage or item position. In Java, there are several methods for iterating over a HashMap. A for loop, foreach, and iterators are the best ways to traverse a HashMap. The lambda expression is used to simplify iterator code when iterating a HashMap with the stream apis in Java 8 and Java 10.

Although a HashMap is not a Collection, it is included in the Collections framework. As a result, the Map interface is designed differently than the Collections interface. A method for iterating over a set of things is called an iterator. 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. From Java 8, the map.foreach method is available. To make coding easier, you can use lambda expressions.

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. This method uses for each approach for the key set collection in the HashMap. The keys are extracted from the HashMap as a set and iterated over with the “for each” 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");
		
		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. This is yet another way to iterate through the Hashmap. HashMap provides a collection of all the keys stored in it in the form of a Set Object. The iterator is based on a collection of key set objects. The while loop will iterate through the keys until the key set is exhausted.

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. The iterator is created on the EntrySet object, which keeps a pointer on the set of Entry objects. The while loop will run until the iterator reaches the end of the collection of entry sets.

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. The pointer will be kept in the HashMap values collection by the Iterator. The while loop will continue to iterate until the iterator reaches the end of the collection values objects. When the iterator.hasNext method reaches the end of the collection, it returns false.

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



Leave a Reply