Given the code fragment:
List<Integer> numbers = Arrays.asList(1, 2, 3); numbers.stream() .map(num -> num*2) //line n1 .peek(System.out::print) //line n2 .count();
What is the result?
B. The code produces no output.
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2
The correct answer is A.
The count() method is a terminal operation, hence the stream will be processed. map() simply doubles each incoming value, peek() uses the System.out::print metref to send its output to console, and then count()… hmm… counts the number of the stream elements that came its way. We, of course, can’t see this number because we didn’t ask for it, but it doesn’t preclude the code from compiling.
As an exercise please re-write the snippet to actually print the count() method’s output. But before doing this, answer the following question: what is the type of the count() method’s return value? Specifically, is it Optional, int, long, Integer or Long? Because you’ll have a question on the exam that tests this aspect, so memorize it well.
One more exercise is to re-code peek()’s arg from metref to a regular lambda expression. Of what type is this lambda?
Answers to the additional exercises and questions to this Problem are here.