Explain forEach vs forEachOrdered in Java 8

By | March 24, 2023

In Java 8, the forEach method is a default method in the Iterable interface that allows you to iterate over each element of a collection and perform an operation on each element. The forEach method takes a Consumer functional interface as an argument, which represents the operation to be performed on each element.

The forEach method doesn’t guarantee the order in which elements will be processed, and the processing of elements may happen concurrently, depending on the underlying implementation of the collection.

On the other hand, the forEachOrdered method was introduced in Java 8 as a method of the Stream interface. It is used to perform a similar operation as forEach, but it guarantees that the elements will be processed in the order they appear in the stream, regardless of the underlying implementation. This means that forEachOrdered does not allow concurrent processing of elements and ensures that the order of processing is the same as the order of elements in the stream.

Here’s an example to illustrate the difference between forEach and forEachOrdered in Java 8:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Using forEach to print each element

System.out.print(“forEach: “);

numbers.forEach(System.out::print);  // output: 12345

// Using forEachOrdered to print each element

System.out.print(“\nforEachOrdered: “);

numbers.stream().forEachOrdered(System.out::print);  // output: 12345

In the above code, we have a list of integers and we use forEach to print each element of the list. As forEach doesn’t guarantee the order of processing, the output may not be in the same order as the original list. In this case, we get the output as 12345.

Next, we use forEachOrdered to print each element of the list. As forEachOrdered guarantees the order of processing, the output will be in the same order as the original list. In this case, we get the output as 12345 again, but this time the order is guaranteed.

So, the key difference between forEach and forEachOrdered is that forEach doesn’t guarantee the order of processing, while forEachOrdered guarantees the order of processing.

In summary, forEach is used to iterate over a collection and perform an operation on each element without guaranteeing the order of processing, while forEachOrdered is used to iterate over a stream and perform an operation on each element in a specified order.

Leave a Reply

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