Given the code fragment:

List<Integer> list1 = Arrays.asList(10, 20);
List<Integer> list2 = Arrays.asList(15, 30);
//line n1

Which code fragment, when inserted at line n1, prints 10 20 15 30?

A.

Stream.of(list1, list2)
.flatMap(list -> list.stream())
.forEach(s -> System.out.print(s + " "));
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 + " "));

题解

Stream 对象的 flatMap 方法可以将串流对象中的元素展开成新的 Stream 对象。

选项 A,正确答案。

选项 B,Stream 对象并没有 intStream 方法。

选项 C,e1 的型态是整数,所以没有 stream 方法。

选项 D,Stream 对象的 flatMapToInt 方法,可以将串流对象中的元素展开成新的 IntStream 对象。所以传入的 mapper 参数的 Lambda 语法,应该要能回传 IntStream 对象才行。如果改成如以下程序,则选项 D 正确:

Stream.of(list1, list2)
.flatMapToInt(list -> list.stream().mapToInt(e -> e))
.forEach(s -> System.out.print(s + " "));