Java 8 lambda foreach Map

You must have heard about Lambda Expression introduced in Java 8. Soon we will cover detail topics on it. But now in this article i will show how to use Lambda expression to iterate Collection.

Before Java 8

class java_5_enhancedForLoop_Map {
	public static void main(String[] args) {

		Map<String, String> jbtObj = new HashMap<String, String>();
		jbtObj.put("Website Name","Java Beginners Tutorial");
		jbtObj.put("Language", "Java");
		jbtObj.put("Topic", "Collection");

		for (Map.Entry<String, String> entry : jbtObj.entrySet()) {
			System.out.println(entry.getKey() + " : "+ entry.getValue());
		}

		// Iterating over collection object using iteration even before Java 5
		Iterator<Entry<String, String>> iterator = jbtObj.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<String, String> thisEntry = (Entry<String, String>) iterator.next();
			Object key = thisEntry.getKey();
			Object value = thisEntry.getValue();
			System.out.println(key+" : "+value);
		}
	}
}

After Java 8 Using Lambda Expression

public class java_8_forEach_Map {
	public static void main(String[] args) {
		Map<String, String> jbtObj = new HashMap<String, String>();
		jbtObj.put("Website Name","Java Beginners Tutorial");
		jbtObj.put("Language", "Java");
		jbtObj.put("Topic", "Collection");

		jbtObj.forEach((key,value) -> System.out.println(key+" :"+value));
	}
}

As you can see with with single line code we can iterate over Map. In the same way we can filter out the result using filters introduced in Lambda.

By | 2016-02-12T11:58:32+00:00 February 12th, 2016|Core Java|1 Comment

About the Author:

One Comment

  1. Darwin Airola August 10, 2016 at 6:49 am - Reply

    Do you have any examples of a map.foreach( (k,v) -> ) where does not print something but, rather, accumulates and returns something? (All of the examples that I have seen only involve printing the values of the map, which is fairly useless for most applications.)

Leave A Comment