I can create a Stream from an array using Arrays.stream(array)
or Stream.of(values)
. Similarly, is it possible to create a ParallelStream directly from an array, without creating an intermediate collection as in Arrays.asList(array).parallelStream()
?
Parallel Streams. Any stream in Java can easily be transformed from sequential to parallel. We can achieve this by adding the parallel method to a sequential stream or by creating a stream using the parallelStream method of a collection: List<Integer> listOfNumbers = Arrays.
stream() A good way to turn an array into a stream is to use the Arrays class' stream() method. This works the same for both primitive types and objects.
The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.
When a stream executes in parallel, the Java runtime partitions the stream into multiple substreams. Aggregate operations iterate over and process these substreams in parallel and then combine the results. When you create a stream, it is always a serial stream unless otherwise specified.
Stream.of(array).parallel() Arrays.stream(array).parallel()
TLDR;
Any sequential Stream
can be converted into a parallel one by calling .parallel()
on it. So all you need is:
parallel()
on it.Long answer
The question is pretty old, but I believe some additional explanation will make the things much clearer.
All implementations of Java streams implement interface BaseStream
. Which as per JavaDoc is:
Base interface for streams, which are sequences of elements supporting sequential and parallel aggregate operations.
From API's point of view there is no difference between sequential and parallel streams. They share the same aggregate operations.
In order do distinguish between sequential and parallel streams the aggregate methods call BaseStream::isParallel
method.
Let's explore the implementation of isParallel
method in AbstractPipeline
:
@Override public final boolean isParallel() { return sourceStage.parallel; }
As you see, the only thing isParallel
does is checking the boolean flag in source stage:
/** * True if pipeline is parallel, otherwise the pipeline is sequential; only * valid for the source stage. */ private boolean parallel;
So what does the parallel()
method do then? How does it turn a sequential stream into a parallel one?
@Override @SuppressWarnings("unchecked") public final S parallel() { sourceStage.parallel = true; return (S) this; }
Well it only sets the parallel
flag to true
. That's all it does.
As you can see, in current implementation of Java Stream API it doesn't matter how you create a stream (or receive it as a method parameter). You can always turn a stream into a parallel one with zero cost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With