0

I have a Stream of objects, of which the first part is to be handled differently from the second part (a simple test will tell when to switch).

I've tried to create the stream and use it first with a takeWhile and then handle the rest of it:

Stream s = [...];

s.takeWhile(simplePredicate).forEach(this::handleFirstPart);
s.forEach(this::handleRest);

It doesn't work: it throws java.lang.IllegalStateException: stream has already been operated upon or closed.

Why can't I keep using the stream after takeWhile decides to stop its processing?

Is there a way to do it?

rslemos
  • 2,454
  • 22
  • 32
  • Related: https://stackoverflow.com/questions/19940319/can-you-split-a-stream-into-two-streams – Garuno Nov 28 '22 at 15:50
  • In case if you expect to perform some side-effects using stream elements like in your example without storing them, it's not possible with streams. If you would try to incorporate the state into the stream using dirty hacks, such solution would be broken in parallel. – Alexander Ivanchenko Nov 28 '22 at 16:11

0 Answers0