The Java forEach() method is a utility function to iterate over a collection such as (list, set or map) and stream. It is used to perform a given action on each the element of the collection.
The forEach()
method has been added in following places:
Iterable
interface – This makesIterable.forEach()
method available to all collection classes exceptMap
Map
interface – This makesforEach()
operation available to all map classes.Stream
interface – This makesforEach()
andforEachOrdered()
operations available to all types of stream.
1. Iterable forEach()
1.1. forEach() Method
The given code snippet shows the default implementation of forEach()
method in Iterable interface.
Internally it uses the enhanced for-loop. So using the new for-loop will give the same effect and performance as forEach()
method.
default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }
The forEach()
method performs the given action
for each element of the Iterable
until all elements have been processed or the action
throws an exception.
Example 1: Java program to iterate over a List using forEach()
List<String> names = Arrays.asList("Alex", "Brian", "Charles"); names.forEach(System.out::println);
Program Output:
Alex Brian Charles
1.2. Creating consumer action
In above example, the action
represents an operation that accepts a single input argument and returns no result. It is an instance of Consumer
interface.
By creating the consumer action like this, we can specify multiple statements to be executed in a syntax similar to a method.
List<String> names = Arrays.asList("Alex", "Brian", "Charles"); Consumer<String> makeUpperCase = new Consumer<String>() { @Override public void accept(String t) { System.out.println(t.toUpperCase()); } }; names.forEach(makeUpperCase);
Program Output:
ALEX BRIAN CHARLES
2. Map forEach()
2.1. forEach() Method
This method performs the given BiConsumer action for each Entry
in this Map
until all entries have been processed or the action throws an exception.
default void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); for (Map.Entry<K, V> entry : entrySet()) { K k; V v; try { k = entry.getKey(); v = entry.getValue(); } catch(IllegalStateException ise) { // this usually means the entry is no longer in the map. throw new ConcurrentModificationException(ise); } action.accept(k, v); } }
Example 2: Java program to iterate over a Map using forEach()
Map<String, String> map = new HashMap<String, String>(); map.put("A", "Alex"); map.put("B", "Brian"); map.put("C", "Charles"); map.forEach((k, v) -> System.out.println("Key = " + k + ", Value = " + v));
Program Output:
Key = A, Value = Alex Key = B, Value = Brian Key = C, Value = Charles
We can also create a custom BiConsumer action which will take key-value pairs from Map
and process each entry one at a time.
BiConsumer<String, Integer> action = (a, b) -> { //Process the entry here as per business System.out.println("Key is : " + a); System.out.println("Value is : " + b); }; Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); map.forEach(action);
Program output.
Key is : A Value is : 1 Key is : B Value is : 2 Key is : C Value is : 3
3. Stream forEach() and forEachOrdered()
In Stream
, forEach()
and forEachOrdered()
are terminal operations.
Similar to Iterable
, stream forEach()
method performs an action for each element of the stream.
For sequential streams, the order of elements (during iteration) is same as the order in the stream source, so the output would be same whether we use forEach()
or forEachOrdered()
.
while using parallel streams, use forEachOrdered()
if order of the elements matter during the iteration. forEach()
method does not gaurantee the element ordering to provide the advantages of parallelism.
Example 3: Java forEach() example to iterate over Stream
In this example, we are printing all the even numbers from a stream of numbers.
List<Integer> numberList = Arrays.asList(1,2,3,4,5); Consumer<Integer> action = System.out::println; numberList.stream() .filter(n -> n%2 == 0) .forEach( action );
Program output.
2 4
Example 4: Java forEachOrdered() example to iterate over Stream
In this example, we are printing all the even numbers from a stream of numbers.
List<Integer> numberList = Arrays.asList(1,2,3,4,5); Consumer<Integer> action = System.out::println; numberList.stream() .filter(n -> n%2 == 0) .parallel() .forEachOrdered( action );
Program output.
2 4
Happy Learning !!
Leave a Reply