Java Stream API: Code Fragment Analysis

Code Analysis: Stream Operations on List of Integers

Question

Given the code fragment: List<Integer> values = Arrays.asList (1, 2, 3); values.stream () .map(n -> n*2)//line n1 .peek(System.out::print) //line n2 .count(); What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The given code fragment creates a list of integers using the Arrays.asList() method and then creates a stream from that list using the stream() method. The map() operation is applied to each element in the stream to double its value, and the resulting stream is passed to the peek() operation to print each element. Finally, the count() method is called on the stream to count the number of elements.

The output of the code will be:

246

Explanation:

  • The map() operation doubles each element in the stream, resulting in a stream of {2, 4, 6}.
  • The peek() operation prints each element in the stream, so the output of System.out::print will be 246.
  • The count() operation counts the number of elements in the stream, which is 3.

Therefore, the correct answer is A. 246.