How to Print Elements of a List in Java Without Loops

Published Jul 31, 2021

Suppose we have a List<String> lst in Java, and we want to print out all elements in the list.

There are many ways to do this.

Iterable forEach()


This method uses the collection’s iterator for traversal. It is designed to exhibit fail-fast behavior, which means a structural modification of the underlying collection during the iteration will result in a ConcurrentModificationException.

This is explained further in the ArrayList docs:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.

Stream forEach()

// Order is maintained;

Stream pipelines may execute either sequentially or in parallel. For instance, creates a sequential stream while Collection.parallelStream() creates a parallel one.

The order is maintained when using stream() piped with forEach().

Parallel Stream forEach()

// Order is not maintained

On its own, the forEach() function does not guarantee order since it can be operating on either a sequential or parallel stream.

The docs go into more detail:

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.

In the case of parallel streams, order is never guaranteed. It is possible that an action is performed in a different thread for different elements, which is not possible in the next case.

Stream forEachOrdered()

// Order is maintained;

If order matters, use forEachOrdered().

The docs explains this function with the following:

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

Parallel Stream forEachOrdered()

// Order is maintained

This method doesn’t make much sense.

The forEachOrdered() function will process elements in the order specified by the source irrespective of a sequential or parallel stream.

More Java Articles