[英]Java stream flatMap with keeping first and second level objects in stream
I was wondering how I could use Java Stream API to flatten a structure where I have an object and a collection of the same type objects nested in it. 我想知道如何使用Java Stream API来扁平化其中包含对象和嵌套相同类型对象的集合的结构。
What I mean is that I have a Component
class which has a field of type List<Component>
. 我的意思是,我有一个
Component
类,该类具有一个List<Component>
类型的字段。 What I would like to do is find a neat, stream solution that would the the same as the following code (I need to end up with a list of all components and nested subcomponents). 我想做的是找到一个整洁的流解决方案,该解决方案与以下代码相同(我需要以所有组件和嵌套子组件的列表结尾)。
List<Component> components = getComponents(id);
List<Component> componentsAndSubcomponents = new ArrayList<>();
for (Component component : components) {
componentsAndSubcomponents.add(component);
componentsAndSubcomponents.addAll(component.getSubComponents());
}
You can use flatMap
with Stream
concatenation: 您可以将
flatMap
与Stream
串联一起使用:
List<Component> componentsAndSubcomponents =
components.stream()
.flatMap(c -> Stream.concat(Stream.of(c),c.getSubComponents().stream()))
.collect(Collectors.toList());
This will map each Component
into a Stream
that contains that Component
followed by all of its sub-components, and flatten all these Stream
s into a flat Stream<Component>
, to be collected into a List<Component>
. 这将每个映射
Component
成Stream
,其中包含Component
,随后所有的子组件,并压平所有这些Stream
s转换为平坦Stream<Component>
,将被收集到一个List<Component>
。
An easy solution is to create an inner stream on the fly, as in: 一个简单的解决方案是动态创建内部流,如下所示:
List<Component> result = components.stream()
.flatMap(comp ->
Stream.concat(Stream.of(comp), comp.getSubComponents().stream()))
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.