对 n 阶树结构进行平面映射:Java 流
Flatmaping a n-order tree structure : Java Streams
假设我有一个非二叉树结构(每个节点可能有 n
个子节点)。从这个意义上讲,使用 java streams?
将整棵树展平为单个列表的好方法是什么?
rootNode.getChildren().stream()
.flatMap(node -> node.getChildren().stream())
.collect(Collectors.toList());
这个例子是我为单级展平所做的,但仍然不包括根节点(这是需要的)。
让我们打电话给您的 class Node
。在 class 中添加方法(假设 getChildren()
从不 return null
):
public Stream<Node> streamAll(){
return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Node::streamAll));
}
然后要获取列表,只需调用
rootNode.streamAll().collect(Collectors.toList());
假设我有一个非二叉树结构(每个节点可能有 n
个子节点)。从这个意义上讲,使用 java streams?
将整棵树展平为单个列表的好方法是什么?
rootNode.getChildren().stream()
.flatMap(node -> node.getChildren().stream())
.collect(Collectors.toList());
这个例子是我为单级展平所做的,但仍然不包括根节点(这是需要的)。
让我们打电话给您的 class Node
。在 class 中添加方法(假设 getChildren()
从不 return null
):
public Stream<Node> streamAll(){
return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Node::streamAll));
}
然后要获取列表,只需调用
rootNode.streamAll().collect(Collectors.toList());