Iterate through a Map in Java

How to iterate through a Map in Java

In this articles, we will explore the different ways to Iterate through a Map in Java. We will start with a simple use case and will explore how we can do this using Java 8 Stream API.

 

Introduction

Iterating through Java Map is very common tasks and we face this tasks daily basis. Java Map API provides keySet(), valueSet() or entrySet() option to fetch content/data from the Map.

The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection view. These Map.Entry objects are valid only for the duration of the iteration.

Entry.getKey() returns the key corresponding to this entry. Let’s explore different options to Iterate through a Map in Java.

 

Example

To start working on the different options, let take a simple Map contains few values. Here is code for the simple Map.

Map<String, String> sampleMap= new HashMap<String,String>();

sampleMap.put("one", "one");
sampleMap.put("two", "two");
sampleMap.put("three", "three");
sampleMap.put("four", "four");
sampleMap.put("five", "five");
sampleMap.put("six", "six");

1.  EntrySet with for Loop 

public void iterateForEach(Map<String, String> sampleMap){
    for(Map.Entry<String,String> mapValue : sampleMap.entrySet()){
        System.out.println(mapValue.getKey()+" :" + mapValue.getValue());
    }
}

In above code, we have we converted Map to entry set and then we iterated through the entries using for each loop.

2.  EntrySet with for Loop 

If you don’t want to use For Each loop, we can convert entrySet() to the iterator and use an iterator to loop through the map content.

public void iterator(Map<String, String> map){
    Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
    while(iterator.hasNext()){
        Map.Entry<String, String> entry = iterator.next();
        System.out.println(entry.getKey()+" :" + entry.getValue());
    }
}

I will not prefer this approach and will go with for each loop.

3.  For Each with Java 8 Lambdas

The introduction of Lambdas in Java 8 provides a more concise and easy to read solution.

public void lambdas(Map<String, String> map){
    map.forEach((key,value) ->System.out.println(key + ":"+ value));
}

One of the interesting thing with above approach is that we don’t need to convert the map to entry set for iteration.

4.  Java 8 Stream API

Stream was introduced in Java 8 as one of the main features, we can use Stream API to iterate through the map.

public void stream(Map<String, String> map){
    map.entrySet().stream().forEach(entry-> System.out.println(entry.getKey() +": "+entry.getValue()));
}

I will not use this since we are converting Map to entry set and iterating through the element which is more or less equivalent to for each loop.

If you want you can use Java 8 Stream API parallel method but I will not cover that in this post.

5.  Performance

For small map size (<=100), Java 8 based for each loop have the best performance. In the case of Map size is greater than 10000 elements, simple for each loop seems to be faster than other approaches.Please execute your own benchmarking before taking a call for your implementation.

6.  Conclusion

In this short post, we covered some of the methods to Iterate through a Map in Java along with few options provided by Java 8. 

All the code of this article is available Over on Github. This is a Maven-based project.

JavaDevJournal

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz