5 ways to Iterate Map in Java using entrySet()

In this post, we will discuss various methods to iterate Map in Java using entrySet() method.

Related Post: 5 ways to Iterate Map using keySet() in Java

We know that Map.entrySet() returns a set of key-value mappings contained in the map. So we can iterate a map using Map.entrySet() which contains both key-value pairs. There are several ways to do that –


1. Using Iterator

Since Map doesn’t extend Collection Interface, it don’t have its own iterator. But Map.entrySet() returns set of key-value mappings and since Set extends Collection Interface, we can get an iterator to it. Now we can easily process each key-value pair by using a simple while loop as shown below:



2. For-each Loop (enhanced for statement)

The for loop also has another variation designed for iteration through Collections and arrays. It is called for-each loop and is available to any object implementing Iterable Interface. As Set extends Collection Interface and Collection extends Iterable Interface, we can use for-each loop to loop through the entrySet. Please note that this approach will also invoke the iterator() method behind the scenes.



3. Java 8 – Iterator.forEachRemaining()

We can also use forEachRemaining() method that is the latest addition to the Iterator Interface in Java 8. It performs the given action for each remaining element until all elements have been processed.

As seen before, we can easily get the Iterator to the Set of Map.Entry. Once we have the Iterator, we can pass the method reference System.out::println or corresponding lambda expression
E -> System.out.println(E) to forEachRemaining() method as shown below:



4. Java 8 – Stream.forEach()

We can use streams in Java 8 to iterate a map by passing method reference or lambda expression to forEach() method of Stream Interface that performs an action for each element of this stream.


We can also use Stream.of to get Stream of Objects –


5. Using toString()

If we just want to display key-value pairs present in the map, we can simply print the string representation of map.entrySet() that returns set of key-value pairs. This approach will even work directly on map as shown below:


or in Java 8 using streams –

Below is a simple Java program that covers all approaches discussed above –


Download   Run Code

We can also use Generics for Iterator and for-each loop method discussed above:


Download   Run Code

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of