How to Print Elements of a List in Java Without Loops


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()

lst.forEach(System.out::println);

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
lst.stream().forEach(System.out::println);

Stream pipelines may execute either sequentially or in parallel. For instance, Collection.stream() 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
lst.parallelStream().forEach(System.out::println);

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
lst.stream().forEachOrdered(System.out::println);

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
lst.parallelStream().forEachOrdered(System.out::println);

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.