Our website loads in split second powered by Schema Theme. Thanks to MyThemeShop

java8 – forEach vs forEachOrdered

With Java8 streams, we take the advantage of parallelism on multi core processor. Java8 has introduced forEach() forEachOrdered() on collections to iterate over a stream of elements, however there is a difference between the two methods.

Quoting from forEach Javadoc:

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

Where the forEachOrdered Javadoc states

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

Java8 forEach() vs forEachOrdered() example