BackendBench
Coffee
Spot the Bug #80

The pipeline that never runs

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: 6

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

What is wrong

Intermediate operations such as map are lazy. Without a terminal operation like collect, forEach or count, nothing is executed, so none of the "checking" lines print.

The fix

ids.stream().map(String::toUpperCase).forEach(id -> System.out.println("checking " + id));

How to avoid it next time

Every pipeline needs a terminal operation. Do not use map for side effects; use forEach.

Want the background? Read Stream operations in depth 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โ† #79#81 โ†’

Frequently asked questions

What is the bug in "The pipeline that never runs"?

Intermediate operations such as map are lazy. Without a terminal operation like collect, forEach or count, nothing is executed, so none of the "checking" lines print. The faulty line is line 6: ids.stream().map(id -> { System.out.println("checking " + id); return id.toUpperCase(); });

How do I fix it?

Replace it with: ids.stream().map(String::toUpperCase).forEach(id -> System.out.println("checking " + id));. Every pipeline needs a terminal operation. Do not use map for side effects; use forEach.

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