2017-11-18 212 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

完成!我試圖找出如何做到這一點嘿嘿 –