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 + " "));