BackendBench
Coffee
Spot the Bug #79

A stream used twice

A easy Java puzzle in the streams and lambdas family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

easyStreams and lambdasbuggy line: 8

Highlighted: line 8. Play this one as a puzzle without the answer.

What is wrong

A stream can be consumed once. After count (a terminal operation) the stream is closed, and the second use throws IllegalStateException: stream has already been operated upon or closed.

The fix

List<String> names = List.of("ann", "bob", "cy"); long count = names.stream().count(); names.stream().forEach(System.out::println);

How to avoid it next time

Keep the source collection and create a new stream per pipeline, or use a Supplier<Stream>.

Want the background? Read Streams in the Java concepts library.

About streams and lambdas

Streams are single-use and lazy, and lambdas can only capture effectively final variables. Side effects inside stream pipelines and parallel streams over shared state are frequent sources of surprise.

In code review: Check whether a stream variable is used twice, whether the terminal operation is present, and whether any lambda mutates outside state.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #78#80 โ†’

Frequently asked questions

What is the bug in "A stream used twice"?

A stream can be consumed once. After count (a terminal operation) the stream is closed, and the second use throws IllegalStateException: stream has already been operated upon or closed. The faulty line is line 8: names.forEach(System.out::println);

How do I fix it?

Replace it with: List names = List.of("ann", "bob", "cy"); long count = names.stream().count(); names.stream().forEach(System.out::println);. Keep the source collection and create a new stream per pipeline, or use a Supplier.

How do I catch streams and lambdas in code review?

Check whether a stream variable is used twice, whether the terminal operation is present, and whether any lambda mutates outside state.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need