[我想知道如何使用Java Stream API来展平其中包含对象和嵌套相同类型对象的集合的结构。
我的意思是,我有一个Component
类,其字段类型为List<Component>
。我想做的是找到一个整洁的流解决方案,该解决方案与以下代码相同(我需要以所有组件和嵌套子组件的列表结尾)。
List<Component> components = getComponents(id);
List<Component> componentsAndSubcomponents = new ArrayList<>();
for (Component component : components) {
componentsAndSubcomponents.add(component);
componentsAndSubcomponents.addAll(component.getSubComponents());
}
您可以将flatMap
与Stream
串联使用:
List<Component> componentsAndSubcomponents =
components.stream()
.flatMap(c -> Stream.concat(Stream.of(c),c.getSubComponents().stream()))
.collect(Collectors.toList());
[这会将每个Component
映射到包含Stream
和其所有子组件的Component
,并将所有这些Stream
展平为展平Stream<Component>
,然后收集到[ C0]。
一种简单的解决方案是动态创建内部流,如:
List<Component>