If this method is called with Stream.of("hi"), how many lines are printed?
public static void print(Stream<String> stream) { Consumer<String> print = System.out::println; stream.peek(print) .peek(print) .map(s -> s) .peek(print) .forEach(print); }
B.
This code does compile.
As an intermediate operation, you are allowed to call peek()
many times in a stream pipeline.
You can even call it multiple times in a row.
While it is common to write System.out::println directly as a parameter to peek()
, nothing prevents you from creating a Consumer variable.
Since the forEach()
method also takes a Consumer, we can reuse it.
The three peek()
intermediate operations and one forEach()
operation total four lines of output.
The map()
operation could be omitted since it simply passes the input through.