Melad Basilius
Melad Basilius

Reputation: 4306

There is no way to create a reference to stream & it’s not possible to reuse the same stream multiple times

Reading article about java 8 stream, and found

Java Streams are consumable, so there is no way to create a reference to stream for future usage. Since the data is on-demand, it’s not possible to reuse the same stream multiple times.

at the same time at the same article

//sequential stream
Stream<Integer> sequentialStream = myList.stream();

//parallel stream
Stream<Integer> parallelStream = myList.parallelStream();

What does it mean of "there is no way to create a reference to stream for future usage" ? aren't sequentialStream and parallelStream references to streams

also what does it mean of "it’s not possible to reuse the same stream multiple times" ?

Upvotes: 2

Views: 265

Answers (1)

Misha
Misha

Reputation: 28133

What it means is that every time you need to operate on a stream, you must make a new one.

So you cannot, for example, have something like:

Class Person {
    private Stream<String> phoneNumbers;

    Stream<String> getPhoneNumbers() {
        return phoneNumbers;
    }
}

and just reuse that one stream whenever you like. Instead, you must have something like

Class Person {
    private List<String> phoneNumbers;

    Stream<String> getPhoneNumbers() {
        return phoneNumbers.stream();  // make a NEW stream over the same data
    }
}

The code snipped you included does just that. It makes 2 different streams over the same data

Upvotes: 5

Related Questions