---
# System prepended metadata

title: flatMap 的用法
tags: [ocpjp]

---

# flatMap 的用法
[參考網站1](http://zhi-bin1985.blogspot.com/2016/08/java-8-stream-flatmap.html)
[參考網站2](https://)

```java=
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 + " "));
- [x] **Answer: A**

:::info
使用flatMap

Stream<Transcript> s1與Stream<Transcript> s2 
=> Stream<Transcript> sTotal

可以把多個stream , 結合成一個stream來處理
:::

```java=
List<Integer> list1 = Arrays.asList(10,20);
List<Integer> list2 = Arrays.asList(15,30);
		
Stream.of(list1,list2).flatMap(list->list.stream()).forEach(s->System.out.println(s));
```

Console:
```
10
20
15
30
```

###### tags: `ocpjp`