Middle
What will this test output? @Test public void test50() { List<Integer> numbers = List.of(1, 2, 3, 4, 5); numbers.stream() .map(x -> { System.out.println(x); return x; }) .filter(x -> x > 2) .map(x -> { System.out.println(x); return x; }) .toList(); }
sobes.tech AI
Answer from AI
This test creates a list of numbers from 1 to 5 and performs sequential processing using the Stream API.
Explanation of output:
- The first
.map(x -> { System.out.println(x); return x; })prints all elements of the list: 1, 2, 3, 4, 5. - Then
.filter(x -> x > 2)passes only numbers greater than 2: 3, 4, 5. - The second
.map(x -> { System.out.println(x); return x; })prints only the filtered elements: 3, 4, 5.
The final output to the console will be:
1
2
3
4
5
3
4
5
Note that streams in Java are lazy, but the terminal operation .toList() triggers execution, so all elements will be processed and printed.