This post will discuss various methods to iterate map using keySet() in Java.

We know that the 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 a value. There are several ways to do that:

1. Using Iterator

Since the map doesn’t extend the Collection interface, it doesn’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. Using for-each loop (Enhanced for statement)

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

3. Using Iterator.forEachRemaining() method

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

4. Using Stream.forEach() method

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

5. Using Stream.of() + toArray() + forEach() method

We can also call forEach operation on stream of objects returned by Stream.of() method:

 
 
Following 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

That’s all about iterating over a Map in Java using the keySet() method.

 
Related Post:

Iterate Map in Java using the entrySet() method