Streams & functional · interview question
What does this print?
What does this code output?Hard
public class Main {
public static void main(String[] args) {
Stream.of(1, 2, 3, 4)
.peek(n -> System.out.print("p" + n + " "))
.filter(n -> n % 2 == 0)
.findFirst()
.ifPresent(n -> System.out.print("found" + n));
}
}Answer and explanation
Correct answer
A. p1 p2 found2
Why
Streams are lazy and evaluated element by element. 1 is peeked then filtered out; 2 is peeked, passes the filter, and findFirst short-circuits, so 3 and 4 are never pulled.
References
Test yourself on Streams & functional
A free test with instant, explained results. No account needed.