Java 8 - Using forEach to iterate map

25/09/2016 Amit Gupta 338 Java

In this article, we will understand how to iterate a map using lambda expression in Java 8.

Prior to Java 8, there were various approaches to iterate map in Java listed below- 

  1. Iterate Map using for-each loop and KeySet
  2. Iterate Map using KeySet Iterator
  3. Iterate Map using EntrySet and for-each loop
  4. Iterate Map using EntrySet and Iterator

For examples refer - Iterate Map prior to Java 8

But in Java 8 lambda expression was introduced. In Java 8, you can loop a Map with forEach method and lambda expression.

The forEach default method is defined in Map interface. The signature of forEach method is - 

default void forEach(BiConsumer<? super K,? super V> action)

This method performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Let us iterate Map in Java 8 using forEach method and lambda expression.

Implementation

import java.util.HashMap;
import java.util.Map;

/**
 * @author Amit Gupta
 *
 */
public class IterateMapExample {

	public static void main(String[] args) {

		Map<Integer, String> hMap = new HashMap<Integer, String>();
		hMap.put(1, "ONE");
		hMap.put(2, "TWO");
		hMap.put(3, "THREE");
		hMap.put(4, "FOUR");
		hMap.put(5, "FIVE");

		hMap.forEach((k, v) -> {
			System.out.println("Key : " + k + " --- " + "Value: " + v);
		});

	}
}

Output

Key : 1 --- Value: ONE
Key : 2 --- Value: TWO
Key : 3 --- Value: THREE
Key : 4 --- Value: FOUR
Key : 5 --- Value: FIVE

In this article, we learnt how to iterate a map using lambda expression in Java 8.

Article tagged as
Author
Author: Amit Gupta
Published On: 25/09/2016
Last revised On: 9/27/2016 10:27:22 PM
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media