Video in progress

Can you use the same stream twice? What happens?

No. After a terminal operation the stream is closed, and touching it again throws IllegalStateException: stream has already been operated upon or closed. If you need it again, get a new stream from the source.

📖 Answer

Stream<String> s = names.stream().filter(n -> n.length() > 3);

long count = s.count();
List<String> list = s.toList();   // IllegalStateException

A stream is like an iterator: it goes through once and it's done. This is deliberate, because the source can be a file or the network, which can't be re-read.

Solutions:

// 1. get a new one from the source each time
long count = names.stream().filter(n -> n.length() > 3).count();

// 2. if you need it several times, use a Supplier
Supplier<Stream<String>> longNames = () -> names.stream().filter(n -> n.length() > 3);
long c = longNames.get().count();
List<String> l = longNames.get().toList();

// 3. or collect into a list once and work with that
List<String> filtered = names.stream().filter(n -> n.length() > 3).toList();

Keeping a Stream as a field or as a return value often leads to exactly this mistake.