1

I need to calculate the ratio of two parts of the big List, wherein the first part contains the second:

Stream<Element> part1 = list.stream().filter(x -> x.getN1() < x.getN2);
int result = part1.filter(y -> y.isRight()).count() / part1.count();

But this code throws the Exception: java.lang.IllegalStateException: stream has already been operated upon or closed

Can I write a code without creating the same part1 stream in result?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
tikhpavel
  • 399
  • 3
  • 10

2 Answers2

1

You can only reuse a collection as it has memoriation of results.

List<Element> part1 = list.stream().filter(x -> x.getN1() < x.getN2).collect(toList());
double result = (double) part1.stream().filter(y -> y.isRight()).count() / part1.size();

A Stream is a builder for some code which is optimised at run time. It's execution isn't as dynamic as it appears.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Streams are not supposed to be reused, or if you want something seemed to it, you can use suppliers as mentioned here : Copy a stream to avoid "stream has already been operated upon or closed" (java 8)

Community
  • 1
  • 1
Rafik Bex
  • 51
  • 7