簡體   English   中英

Java flatMap - 有什么區別stream.of()和collection.stream()

[英]Java flatMap - whats the difference stream.of() and collection.stream()

我正在嘗試理解flatMapflatMap(x->stream.of(x) )不會使流平坦, flatMap(x->x.stream())可以工作並提供所需的結果。 有人可以解釋兩者之間的區別嗎?

import java.util.*;
import java.util.stream.*;

class TestFlatMap{

    public static void main(String args[]){
        List<String> l1 = Arrays.asList("a","b");
        List<String> l2 = Arrays.asList("c","d");

        Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));

        Stream.of(l1, l2).flatMap((x)->x.stream()).forEach((x)->System.out.println(x));
    }

}

輸出:

[a, b]
[c, d]
a
b
c
d

Stream.of(x)生成單個元素的流 - x 因此, flatMap返回Stream<List<String>>而不是Stream<String>

另一方面, x.stream() ,其中xCollection<E>返回一個Stream<E>其源是Collection的元素,因此在您的情況下,它返回一個Stream<String> ,它允許flatMap生成一個Stream<String>包含所有String S IN的所有List<String>源第Stream

你可以在Javadoc中看到:

<T> Stream<T> java.util.stream.Stream.of(T t)
返回包含單個元素的順序Stream。

Stream<E> stream()
返回以此集合為源的順序Stream。

你想到的是這個:

Stream.of(l1, l2)
      // String[]::new isn't really needed in this simple example,
      // but would be in a more complex one...
      .flatMap((x)->Stream.of(x.toArray(String[]::new)))
      .forEach((x)->System.out.println(x));

這也會產生a a, b, c, d的扁平流a, b, c, d如你所料。 Stream.of()有兩種形式:

因為,當將List傳遞給Stream.of() ,唯一適用的重載是獲取單個值的重載,您獲得了Stream<List<String>>而不是預期的Stream<String>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM