使用流获取层次结构中所有项目的名称

Kar*_*yap -3 java collections loops java-stream

class ParentItem {
    String itemName;  //I want to get this property for all the objects in hierarchy
    Integer itemCode;
    List<ParentItem> childItem;
}
Run Code Online (Sandbox Code Playgroud)

我想使用流获取所有项目的名称(ParentItem 名称、ChildItem 名称、GrandChildItemName),如何实现?假设 ChildItem 也有一个 Child,这意味着 ParentItem 有一个 GrandChild!所以嵌套有 3 层。如何实现这一目标?

Tho*_*mas 5

尝试以下方法来递归地平面映射子流:

Stream<ParentItem> flatMapChildren(ParentItem item ) {
    return Stream.concat( //flatMap replaces the item in the stream so we need concat() to keep it
         Stream.of(item), //create a 1-element stream for the item that gets replaced
         item.childItem.stream() //create a stream for the children 
                       .flatMap(YourClass::flatMapChildren) //recursively add their children
    );
}
Run Code Online (Sandbox Code Playgroud)

然后在您的顶级流上使用它:

List<ParentItem> topLevel = ....;
Stream<String> streamOfAllNames = 
  topLevel.flatMap(YourClass::flatMapChildren)
          .map(ParentItem::getName);
Run Code Online (Sandbox Code Playgroud)

注意:为了简单起见,该实现不包含空检查等。将它们添加到您的实际代码中。