5 ways to Iterate Map using keySet() in Java

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

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

We know that keySet() method returns a Set view of the keys contained in the map. So we can iterate a map using keySet() and for each key calling map.get(key) to fetch value. There are several ways to do that –


1. Using Iterator

Since Map doesn’t extend Collection Interface, it don’t have its own iterator. Since Set extends the Collection Interface, we can get an iterator to set of keys returned by keySet(). Now we can easily process each key 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 keySet. 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.



4. Java 8 – Stream.forEach()

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



5. Java 8 – Stream.of() + toArray() + forEach()

We can also call forEach operation on Stream of Objects returned by Stream.of() method –


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