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.
  • 87,500
  • 20
  • 164
  • 172
tikhpavel
  • 379
  • 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
  • 513,304
  • 74
  • 731
  • 1,106
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
  • 41
  • 7