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.
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
This is explained further in the
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.
// 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
// 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.
// Order is maintained lst.stream().forEachOrdered(System.out::println);
If order matters, use
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.
// Order is maintained lst.parallelStream().forEachOrdered(System.out::println);
This method doesn’t make much sense.
forEachOrdered() function will process elements in the order specified by the source irrespective of a sequential or parallel stream.
More Java Articles
- How to Remove the Last Character in a String in Java
- How to Remove the First Character in a String in Java
- How to Split a String Over Only the First Occurrence in Java
- How to Get the Substring Before a Character in Java
- How to Pass Dynamic Number of Parameters in Java
- How to Use Generics with Abstract Classes in Java For Different Parameter Types
- How to Replace the String Between Two Characters in Java
- How to Ignore Test Cases in JUnit
- How to Add Multiple Elements to List At Once in Java