[英]Java flatMap - whats the difference stream.of() and collection.stream()
[英]Java 8. Difference between collection.stream() and Stream.of(collection)
你能解釋一下嗎? 為什么
Stream.of(l1, l2).flatMap((x)->x.stream()).forEach((x)->System.out.println(x));
和
Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));
是不同的?
Stream
沒有Stream.of(Collection)
方法。 它確實有一種方法
static <T> Stream<T> of(T t)
如果將Collection
傳遞給此方法,您將獲得包含一個元素( Collection
)的Stream<Collection>
,而不是集合元素的流。
舉個例子,試試這個:
List<Integer> l1 = Arrays.asList(1, 2, 3);
List<Integer> l2 = Arrays.asList(4, 5, 6);
Stream.of(l1, l2).flatMap((x)->x.stream()).forEach((x)->System.out.println(x));
Stream.of(l1, l2).flatMap((x)->Stream.of(x)).forEach((x)->System.out.println(x));
第一個版本打印:
1
2
3
4
5
6
第二個版本打印:
[1, 2, 3]
[4, 5, 6]
請注意,如果arr
是Object[]
您可以使用 Stream.of(arr)
來獲取數組元素的流。 這是因為有另外一個版本of
使用可變參數。
static <T> Stream<T> of(T... values)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.