An array of three that counts as one
A hard 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.
Highlighted: line 6. Play this one as a puzzle without the answer.
What is wrong
Stream.of takes varargs of objects. An int[] is a single object, not a list of Integers, so the stream has one element and the program prints 1. The compiler does not complain because an array is an Object.
The fix
How to avoid it next time
For primitive arrays use Arrays.stream or IntStream.of. Stream.of works with object arrays.
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
Frequently asked questions
What is the bug in "An array of three that counts as one"?
Stream.of takes varargs of objects. An int[] is a single object, not a list of Integers, so the stream has one element and the program prints 1. The compiler does not complain because an array is an Object. The faulty line is line 6: long n = Stream.of(numbers).count();
How do I fix it?
Replace it with: long n = java.util.Arrays.stream(numbers).count(); // or IntStream.of(numbers). For primitive arrays use Arrays.stream or IntStream.of. Stream.of works with object arrays.
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.