How to Iterate Any Map in Java

Video Tutorial
FREE
HashMap Introduction thumbnail
This video belongs to
Java DSA Course - Master the Fundamentals and Beyond
12 modules
Certificate
Topics Covered

In Java, Maps cannot be iterated directly using iterators since they are not Collections. There are mainly five ways to iterate over a Map in Java. This article explores each method, discussing their pros and cons. Before delving into the different methods, It is important to understand the Map.Entry<K, V> interface. These iteration techniques are applicable to all Map implementations in Java (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.).

Iterate over Map.entrySet() Using For-Each Loop

We shall now look at the simple use of an enhanced-for loop where the concept of keySet(), as well as values() method, will also be put into use. But initially, it’s important to see how enhanced-for loop works, so go through its syntax and simple implementation.

Syntax:

Example:

We need to mention the data type according to which enhanced-for loop will iterate, it makes the code more understandable.

We'll iterate the keys with the help of enhanced-for loop:

For entrySet(), we'll use an enhanced-for loop in this manner:

Imagine a scenario where we just have to fetch the names of prisoners. It can be done by using keySet() in maps. Otherwise, we can use values() to fetch the list of all values:

Output:

Iterate over Keys or Values Using keySet() and values() Methods

If it is the collections in Java we’re discussing, the knowledge of Iterator is of utmost importance.

Iterator that can read as well as remove objects but is a unidirectional cursor (works in the forward direction only).

It can be used on all Collection objects and is a universal cursor. It is an interface that uses the iterator() method available in the Collection interface.

Syntax:

E is the data type of the returned element and c refers to a Collection object.

Iterator interface also has four methods, of which we’ll be using these two in our examples.

  • hasNext(): This method returns true if there are more elements in Collections.

    Syntax:

  • next(): This method returns the next element available for iteration. If there isn’t any more element available, it’d throw NoSuchElementException.

    Syntax:

The hasNext() method is put as the condition for the while loop which returns true if there are more elements to iterate. Eventually, we would print the elements by calling the next element once in each iteration.

Here's the final code with iterator()

Output:

The next two methods will also demonstrate the use of Iterator with keySet as well as entrySet.

Iterate Using Iterators over Map.Entry<K, V>

Using iterators over Map.Entry<K, V> does offer advantages, particularly in scenarios where you need to modify the map while iterating over it. This can be useful when you need to filter or manipulate the map's contents based on certain conditions. Additionally, iterators provide more control over the iteration process compared to for-each loops, allowing you to perform more complex operations if needed.

entrySet is the set that comprises all key-value pairs in the map. 

Syntax:

Now, there’s another interface that will be used here: Entry interface.

Since a map is defined as a group of key-value pairs and each pair is referred to as an entry, we usually define Map as a collection of entry objects. The Entry interface consists of a few methods to access all the entry objects.

  • K getKey(): This method would return the key for the indicated entry. If the entry is not present in the map, it will throw IllegalStateException.K is the corresponding key that would be returned.
  • V getValue(): This method would return the value for the indicated map entry. V is the value returned by calling this method.

These entry objects originated from the Entry interface and exist inside the Map interface.  

Therefore, we’ll use its nested version by denoting it as Map.Entry interface in our example. The iterator used for entrySet in our example would be:

Output:

Iterate Using forEach() Method

This method use forEach() and lambda expression.

A lambda expression simply reduces the hassle of writing the entire line of code that contains a method name. Instead, you can simply mention the parameters followed by the expression. And surprisingly, it will work the same as a method. We just need to mention parameters and a lambda expression will help us yield a value. There is an additional example given below to give you a glimpse of the lambda expression.

Moreover, we need to use a forEach loop. forEach() is a method to iterate the Collection elements one by one. Its default implementation is present in the Iterable interface.

Output:

Here, the forEach loop will take the (key, value) as a parameter and use it in the expression to print the result. In our case, we'll use:

Output:

Iterate over Keys and Getting Values

This approach allows direct access to both keys and values simultaneously, significantly reducing the time complexity compared to accessing values individually. By leveraging this method, you can streamline your code and improve its performance, making it a preferred practice in practical implementations.

Output:

Conclusion

  • In this article, we have seen how to iterate over a map in Java.
  • Maps in Java cannot be iterated directly using iterators since they are not Collections.
  • There are different methods to iterate a map in Java as using iterator(), using Lambda expression, foreach, hasNext() etc.