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.

1 Comment Java 8 lambda foreach Map

  1. Darwin Airola

    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.)

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.