flatMap() Effect:
flatMap() is used to transform each element of a stream into a stream of elements and then flatten those streams into a single stream.
When applied to your example [[A, A, A], [B, B, B], [C, C, C]], flatMap() will transform it into [A, A, A, B, B, B, C, C, C], which is a single flat stream of elements.
It effectively "flattens" the nested structure by merging the individual streams into one.
flatMap() 用於將stream中的每個元素轉換為stream of elements,
然後將這些流 展平 (flatten) 為single stream。
當應用於示例[[A, A, A], [B, B, B], [C, C, C]] 時,flatMap() 會將其轉換為[A, A, A, B, B, B , C, C, C],這是單個扁平元素流。
它通過將各個流合併為一個,有效地“展平”嵌套結構。
```java=
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("A", "A", "A"),
Arrays.asList("B", "B", "B"),
Arrays.asList("C", "C", "C")
);
List<String> flatList = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flatList);
// Output: [A, A, A, B, B, B, C, C, C]
```
map() Effect:
map() is used to transform each element of a stream into another element, but it doesn't flatten nested collections.
When applied to your example, [[A, A, A], [B, B, B], [C, C, C]], map() will transform each inner list into a different list of elements, resulting in [[A, A, A], [B, B, B], [C, C, C]], which still maintains the nested structure.
It doesn't flatten the inner lists into a single flat list.
map() 用於將流的每個元素轉換為另一個元素,但它不會展平嵌套集合。
當應用於您的示例時, [[A, A, A], [B, B, B], [C, C, C]],map() 會將每個內部列表轉換為不同的元素列表,從而產生 [ [A, A, A], [B, B, B], [C, C, C]],仍然保持嵌套結構。
它不會將內部列表展平為單個平面列表。
```java=
List<List<String>> nestedList = Arrays.asList(
Arrays.asList("A", "A", "A"),
Arrays.asList("B", "B", "B"),
Arrays.asList("C", "C", "C")
);
List<List<String>> mappedList = nestedList.stream()
.map(innerList -> innerList.stream().map(item -> item).collect(Collectors.toList()))
.collect(Collectors.toList());
System.out.println(mappedList);
// Output: [[A, A, A], [B, B, B], [C, C, C]]
```
So, in summary, flatMap() is used for ==flattening nested collections==,
while map() is used for ==transforming elements without changing the structure==.
因此,總而言之,flatMap() 用於展平嵌套集合,而 map() 用於在不改變結構的情況下轉換元素。