Soban Soundararajan
Soban Soundararajan

Reputation: 493

How can I create a parallel stream from an array?

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

Upvotes: 35

Views: 14517

Answers (2)

Eugene
Eugene

Reputation: 120968

Stream.of(array).parallel() 

or

Arrays.stream(array).parallel()

Upvotes: 56

ETO
ETO

Reputation: 7279

TLDR;

Any sequential Stream can be converted into a parallel one by calling .parallel() on it. So all you need is:

  1. Create a stream
  2. Invoke method 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.

Upvotes: 10

Related Questions