How to iterate a Map in Java

This tutorial shows several ways for iterating a Map in Java.

1- Entry Set

The common way for iterating a Map in Java is through entrySet() method as the following:

2- Iterator

You can also use entrySet() along with iterator() methods to iterate a Map through an Iterator:

3- keySet()

Using keySet() method, you can retrieve all the keys of the map and then get their corresponding value:

4- values()

You can use values() method to retrieve all the values as a Collection without their corresponding keys.

5- Java 8

With Java 8, you can iterate over a Map through one line using forEach() method:

 

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar