Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java stream flatMap,在流中保留第一级和第二级对象_Java_Java Stream_Flatmap - Fatal编程技术网

Java stream flatMap,在流中保留第一级和第二级对象

Java stream flatMap,在流中保留第一级和第二级对象,java,java-stream,flatmap,Java,Java Stream,Flatmap,我想知道如何使用Java Stream API来扁平化一个结构,其中嵌套了一个对象和一组相同类型的对象 我的意思是我有一个组件类,它有一个类型为列表的字段。 我想做的是找到一个整洁的流式解决方案,它与下面的代码相同(我需要一个所有组件和嵌套子组件的列表) List components=getComponents(id); List Components和SubComponents=new ArrayList(); 用于(组件:组件){ 组件和子组件。添加(组件); addAll(compone

我想知道如何使用Java Stream API来扁平化一个结构,其中嵌套了一个对象和一组相同类型的对象

我的意思是我有一个
组件
类,它有一个类型为
列表
的字段。 我想做的是找到一个整洁的流式解决方案,它与下面的代码相同(我需要一个所有组件和嵌套子组件的列表)

List components=getComponents(id);
List Components和SubComponents=new ArrayList();
用于(组件:组件){
组件和子组件。添加(组件);
addAll(component.getSubComponents());
}

您可以将
flatMap
流连接使用:

List<Component> componentsAndSubcomponents =
    components.stream()
              .flatMap(c -> Stream.concat(Stream.of(c),c.getSubComponents().stream()))
              .collect(Collectors.toList());
列出组件和子组件=
components.stream()
.flatMap(c->Stream.concat(Stream.of(c),c.getSubComponents().Stream())
.collect(Collectors.toList());

这将把每个
组件
映射成一个
,该流包含
组件
,然后是它的所有子组件,并将所有这些
展平成一个平面
,收集到
列表
中一个简单的解决方案是动态创建一个内部流,如:

List<Component> result = components.stream()
    .flatMap(comp -> 
        Stream.concat(Stream.of(comp), comp.getSubComponents().stream()))
    .collect(Collectors.toList());
List result=components.stream()
.flatMap(组件->
Stream.concat(Stream.of(comp),comp.getSubComponents().Stream())
.collect(Collectors.toList());
List<Component> result = components.stream()
    .flatMap(comp -> 
        Stream.concat(Stream.of(comp), comp.getSubComponents().stream()))
    .collect(Collectors.toList());