1Z0-809 practice question 25 of 25

Given the code fragment: List list1 = Arrays.asList(10, 20); List list2 = Arrays.asList(15, 30); //line n1 Which code fragment, when inserted at line n1, prints 10 20 15 30?

Full set: 196 questions
Answer options
A: Stream.of(list1, list2).flatMap(list -> list.stream()).forEach(s -> System.out.print(s + “ “)); Correct answer
B: Stream.of(list1, list2).flatMap(list -> list.intStream()).forEach(s -> System.out.print(s + “ “));
C: list1.stream().flatMap(list2.stream().flatMap(e1 -> e1.stream()).forEach(s -> System.out.println(s + “ “));
D: Stream.of(list1, list2).flatMapToInt(list -> list.stream()).forEach(s -> System.out.print(s + “ “));
Correct Answer:
A. Stream.of(list1, list2).flatMap(list -> list.stream()).forEach(s -> System.out.print(s + “ “));
Explanation

The goal is to create a single stream of integers from two separate lists and then print them. Stream.of(list1, list2) creates a Stream<List>. The flatMap operation is used to transform this stream of lists into a single, "flattened" Stream. The lambda expression list -> list.stream() provides the logic for this transformation, turning each list into a stream of its elements. Finally, forEach iterates through the flattened stream and prints each integer.

Why Incorrect

B. The List interface does not have an intStream() method. This code would result in a compilation error.
C. This code is syntactically incorrect. The argument to the first flatMap is an expression ending in forEach, which returns void, not a Stream.
D. The flatMapToInt method requires a function that returns an IntStream. The lambda list -> list.stream() returns a Stream, causing a type mismatch and a compilation error.

References

1. Oracle, "Java SE 8 API Documentation, java.util.stream.Stream interface, flatMap(Function<? super T, ? extends Stream> mapper) method". The documentation describes flatMap as returning "a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element."

2. Oracle, "The Java Tutorials, Aggregate Operations, The flatMap Operation". This tutorial provides examples of using flatMap to flatten complex structures into a single stream.

Scroll to Top