我可以转换流< List< X>>到流< X>? [英] Can I transform a Stream<List<X>> to a Stream<X>?
本文介绍了我可以转换流< List< X>>到流< X>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是可能的(伪Java):
Is this possible (pseudo-Java):
someList = [
[1,2],
[3,4]
];
Stream<List<X>> a = someList.stream();
Stream<X> b = a.whatever(...);
assert b.collect(list).equals([1,2,3,4]);
更常见的是,流上是否有操作可以增加流中的元素数量(而不是减少,因为过滤器
确实如此)?
Put more generally, is there an operation on a stream that can increase the number of elements in the stream (rather than decrease, as filter
does)?
推荐答案
是的。 flatMap
这样做。
Stream<X> b = someList.stream().flatMap(l -> l.stream());
假设 someList
是列表<列表< X>>
, flatMap
会将内部列表的所有元素展平为单个Stream。
Assuming that someList
is a List<List<X>>
, flatMap
would flatten all the elements of the internal lists into a single Stream.
这篇关于我可以转换流< List< X>>到流< X>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文