![](/img/trans.png)
[英]Java 8. Difference between collection.stream() and Stream.of(collection)
[英]Java flatMap - whats the difference stream.of() and collection.stream()
我正在嘗試理解flatMap
: flatMap(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()
,其中x
是Collection<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()
有兩種形式:
Stream.of(T)
采用單個值,如Eran所述 Stream.of(T...)
取一個數組 (不是你Stream.of(T...)
的List
) 因為,當將List
傳遞給Stream.of()
,唯一適用的重載是獲取單個值的重載,您獲得了Stream<List<String>>
而不是預期的Stream<String>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.