Java8 Lambda:连接列表

2022-01-22 00:00:00 java-8 java java-stream

我正在尝试连接流列表并对其进行处理.

I am trying to concat list of a stream and process it.

class A {
    public List<B> bList;
}
List<A> aList;
aList.stream().map(a -> a.bList)....

这里我得到了几个 b 列表.

Here i get several list of b.

但是,我想将我所有的 b 都收集在一个列表中.有什么想法吗?

But, I would like to collect all my b in only one list. Any ideas ?

推荐答案

这就是 flatMap 的用途:

That's what flatMap is for :

List<B> bList = aList.stream()
                     .flatMap(a -> a.bList.stream())
                     .collect(Collectors.toList());

相关文章