forEach() method in Java 8
A forEach() method is a utility method to iterate over the collection like list, set or map and stream. It iterate collection or stream element by element. It takes either predefine function or lambda expression as a parameter. It does not return any value from the function.

The forEach() method has been added in following places:

1. Iterable forEach()2. Map forEach()3. Stream forEach()

Iterable forEach()

An Iterable interface allows to iterate elements using forEach() method. Internally it uses the enhanced for-each loop, so this method produce same result and performance. Hence, an implementation classes of Iterable interface can use to iterate elements using forEach() method.
Iterable.java class
 1 default void forEach(Consumer<? super T> action) {
 2 	Objects.requireNonNull(action);
 3 	for (T t : this) {
 4 		action.accept(t);
 5 	}
 6 }
In the above syntax, the forEach() accept parameter of type Consumer that perform the given action for each element of the Iterable, until all elements have been processed or the action throws an exception. A Consumer Interface can be either method reference or lambda expression.
Iterable forEach()
 1 package com.java;
 2 
 3 import java.util.Arrays;
 4 import java.util.List;
 5 
 6 public class Example {
 7     public static void main(String[] args) {
 8 
 9         List<String> names = Arrays.asList("Welcome", "to", "Java");
 10         names.forEach(System.out::println);
 11     }
 12 }
In the above example, a List object is created by passing a initial values. A List class is a derived class of Iterable interface. A forEach() method is called by passing a method reference of System.out println() method. It iterate each element and prints elements.
Output
 1 Welcome
 2 to
 3 Java

Map forEach()

An Iterable interface also allows to iterate Map collection using forEach() as it derived class of Iterable iterface. It performs the given BiConsumer action that accept key-value pair type object, It is a instance of Entry of the Map until all entries have been processed or the action throws an exception. It accept action that can be either method reference or a lambda expression.
Map.java
 1 default void forEach(BiConsumer<? super K, ? super V> action) {
 2 	Objects.requireNonNull(action);
 3 	for (Map.Entry<K, V> entry : entrySet()) {
 4 		K k;
 5 		V v;
 6 		try {
 7 			k = entry.getKey();
 8 			v = entry.getValue();
 9 		} catch(IllegalStateException ise) {
 10 			// this usually means the entry is no longer in the map.
 11 			throw new ConcurrentModificationException(ise);
 12 		}
 13 		action.accept(k, v);
 14 	}
 15 }
In the above syntax, a forEach() method accept BiConsumer interface instance that has key-value pair data type. It can be either any existing method reference or a lambda expression that will be executed for each iterable elements. It does not returns any value.
map forEach() method
 1 package com.examples;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 public class Example {
 7 	public static void main(String[] args) {
 8 		Map<String, String> map = new HashMap<String, String>();
 9 
 10 		map.put("key1", "Welcom");
 11 		map.put("key2", "to");
 12 		map.put("key3", "Java");
 13 		 
 14 		map.forEach((k, v) -> 
 15 			System.out.println("Key = " + k + ", Value = " + v));
 16 	}
 17 }
In the above example, a Map object is created that store key and value of string type. A value in inserted into the map by using method put(). A forEach() method is called by passing a lambda expression that prints key and value of each element. It calls specified lambda expression for each elements of the map.
Output
 1 Key = key1, Value = Welcome
 2 Key = key2, Value = to
 3 Key = key3, Value = Java

Stream forEach()

A Stream also provide method forEach() which allows to iterate Steam element. It is a terminal operation, an operation that does not returns a Steam object are terminal operation. As forEach() method does not return any value. It provides two terminal operation methods forEach() and forEachOrdered(). Similar to Iterable interface, a stream forEach() method also allows to specify action that can be either method reference or a lambda expression.
Stream forEach()
 1 package com.java;
 2 
 3 import java.util.Arrays;
 4 import java.util.List;
 5 import java.util.function.Consumer;
 6 
 7 public class Example {
 8     public static void main(String[] args) {
 9 
 10         List<Integer> numberList = Arrays.asList(10, 25, 30, 45, 50);
 11 
 12         Consumer<Integer> action = System.out::println;
 13         numberList.stream().filter(n -> n % 2 == 0)
 14                 .forEach(action);
 15     }
 16 }
In the above example, a List object is created with initial values. A Consumer object is created by assigning method reference of System.out println() method. A List object is converted to stream using stream() method. A Stream filter() method called by passing a lambda expression that filter elements which are divisible by 2 and return Steam object of filtered elements. A forEach() method called by a Consumer object that print elements.
To iterate in parallel streams, use forEachOrdered() if order of the elements matter during the iteration. forEach() method does not guarantee the element ordering to provide the advantages of parallelism.
Output
 1 10
 2 30
 3 50

forEachOrdered() method

Stream forEachOrdered()
 1 package com.java;
 2 
 3 import java.util.Arrays;
 4 import java.util.List;
 5 import java.util.function.Consumer;
 6 
 7 public class Example {
 8     public static void main(String[] args) {
 9 
 10         List<Integer> numberList = Arrays.asList(10,25,30,45,50);
 11 
 12         Consumer<Integer> action = System.out::println;
 13         numberList.stream().filter(n -> n % 2  == 0)
 14                 .parallel().forEachOrdered(action);
 15     }
 16 }
In the above example, a forEachOrdered() method used to perform parallel processing on Steam object. A forEachOrdered() method receives Steam elements of parallel processing that prints element by using Consumer object.
Output
 1 10
 2 30
 3 50
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us