2017-11-18 188 views
3

我试图让组件列表属于项目的特定名单列表中的元素。如何获得元素的平面列表属于使用Java流

由于我开始使用流,我无法弄清楚如何做到这一点。

projects.stream() 
     .map(p -> p.getComponents()) 
     .collect(Collectors.toList()); 

由于Project.getComponents()返回Collection<ProjectComponent>以前的代码将返回List<Collection<ProjectComponent>>但我想回到一个List<ProjectComponent>我该怎么办呢?

亲切的问候。

回答

9

使用flatMap

projects.stream() 
     .flatMap(p -> p.getComponents().stream()) 
     .collect(Collectors.toList()); 

flatMap将主要从压扁的Stream<Stream<R>>嵌套流即对Stream<R>在这种情况下,你再收集流元素融入一个List<ProjectComponent>

+1

它的工作原理就像一个魅力。 非常好,非常感谢;) –

+0

杰克,请将标记答案作为有效 –

+0

完成!我试图找出如何做到这一点嘿嘿 –

相关问题