T
- 元素类型public abstract class HierarchyIterator<T> extends Object implements Iterator<T>
用于迭代层级结构(比如树或图)的迭代器,
支持广度优先
与深度优先
两种遍历模式。
迭代器仅适用于访问层级结构,因此不支持Iterator.remove()
方法。
要构建树或者操作数,请参见BeanTree
或TreeUtil
。
该迭代器侧重于打通图或树这类数据结构与传统集合间的隔阂,
从而支持通过传统可迭代集合的方式对树或图中的节点进行操作。
比如:
Tree root = // 构建树结构
// 搜索树结构中所有级别为3的节点,并按权重排序
List<Tree> thirdLevelNodes = StreamUtil.iterateHierarchies(root, Tree:getChildren)
.filter(node -> node.getLevel() == 3)
.sorted(Comparator.comparing(Tree::getWeight))
.toList();
Modifier and Type | Field and Description |
---|---|
protected Set<T> |
accessed
已经访问过的列表
|
protected Function<T,Collection<T>> |
elementDiscoverer
下一层级节点的获取方法
|
protected Predicate<T> |
filter
节点过滤器,不匹配的节点与以其作为根节点的子树将将会被忽略
|
protected LinkedList<T> |
queue
当前待遍历的节点
|
Modifier and Type | Method and Description |
---|---|
static <T> HierarchyIterator<T> |
breadthFirst(T root,
Function<T,Collection<T>> nextDiscoverer)
获取一个迭代器,用于按广度优先迭代层级结构中的每一个结点
|
static <T> HierarchyIterator<T> |
breadthFirst(T root,
Function<T,Collection<T>> nextDiscoverer,
Predicate<T> filter)
获取一个迭代器,用于按广度优先迭代层级结构中的每一个结点
|
protected abstract void |
collectNextElementsToQueue(Collection<T> nextElements)
将下一层级的节点搜集到队列
|
static <T> HierarchyIterator<T> |
depthFirst(T root,
Function<T,Collection<T>> nextDiscoverer)
获取一个迭代器,用于按深度优先迭代层级结构中的每一个结点
|
static <T> HierarchyIterator<T> |
depthFirst(T root,
Function<T,Collection<T>> nextDiscoverer,
Predicate<T> filter)
获取一个迭代器,用于按深度优先迭代层级结构中的每一个结点
|
boolean |
hasNext()
是否仍有下一个节点
|
T |
next()
获取下一个节点
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
forEachRemaining, remove
protected final Function<T,Collection<T>> elementDiscoverer
protected final LinkedList<T> queue
public static <T> HierarchyIterator<T> breadthFirst(T root, Function<T,Collection<T>> nextDiscoverer, Predicate<T> filter)
T
- 元素类型root
- 根节点,根节点不允许被filter
过滤nextDiscoverer
- 下一层级节点的获取方法filter
- 节点过滤器,不匹配的节点与以其作为根节点的子树将将会被忽略public static <T> HierarchyIterator<T> breadthFirst(T root, Function<T,Collection<T>> nextDiscoverer)
T
- 元素类型root
- 根节点,根节点不允许被filter
过滤nextDiscoverer
- 下一层级节点的获取方法public static <T> HierarchyIterator<T> depthFirst(T root, Function<T,Collection<T>> nextDiscoverer, Predicate<T> filter)
T
- 元素类型root
- 根节点,根节点不允许被filter
过滤nextDiscoverer
- 下一层级节点的获取方法filter
- 节点过滤器,不匹配的节点与以其作为根节点的子树将将会被忽略public static <T> HierarchyIterator<T> depthFirst(T root, Function<T,Collection<T>> nextDiscoverer)
T
- 元素类型root
- 根节点,根节点不允许被filter
过滤nextDiscoverer
- 下一层级节点的获取方法public boolean hasNext()
protected abstract void collectNextElementsToQueue(Collection<T> nextElements)
Copyright © 2025. All rights reserved.