需求:根据条件检索获取当前数据的父节点路径
树结构如下: 命中节点:3、9、6、11 命中节点路径树:
1 1
/ | \ / | \
2 3 4 2 3 4
/ \ / \ / \ / \ /
5 6 7 8 9 10 5 6 9
/ \ / \ /
11 12 13 14 11
/ \
15 16
整体解决思路:
参数:
- 树平铺的列表nodeList;
- 命中节点的集合ids;
- 接收命中节点所有路径的列表newNodes;
解决方案:
- 根据命中节点的集合ids 获取命中节点的数据集合hitList;
List<SearchTree > hitList= list.stream().filter(item -> ids.contains(item.getId())).collect(Collectors.toList());
- 对集合hitList进行遍历,遍历过程中,判断newNodes中是否包含了当前节点对象currentNode;
2.1、如果包含了,则继续往下遍历;
2.2、如果不包含,将当前对象放入newNodes中;
-------进入do…while:
-------根据当前对象的pid获取父节点,并赋值给当前节点对象currentNode;
-------判断newNodes中是否包含了当前节点对象currentNode(非空),
-------2.2.1、如果包含了、则跳出当前循环;
-------2.2.2、如果不包含、将当前对象放入newNodes中;
-------2.2.3、判断当前节点对象currentNode的Pid是否为空串,
-----------------如果为空则跳出do…while,否则继续do…while。
for (SearchTree currentNode : hitList) {
if (!newNodes.contains(currentNode)) {
newNodes.add(currentNode);
do {
currentNode = map.get(currentNode.getPid());
if (null != currentNode) {
if (newNodes.contains(currentNode)) break;
newNodes.add(currentNode);
}
} while (!"".equals(currentNode.getPid()));
}
}
完整代码如下:
public static List<SearchTree> hitPathList(List<SearchTree> list, Set<String> ids) {
List<SearchTree> newNodes = new ArrayList<>();
List<SearchTree> hitList = list.stream().filter(item -> ids.contains(item.getId())).collect(Collectors.toList());
Map<String, SearchTree> map = list.stream().collect(Collectors.toMap(SearchTree::getId, Function.identity()));
for (SearchTree currentNode : hitList) {
if (!newNodes.contains(currentNode)) {
newNodes.add(currentNode);
do {
currentNode = map.get(currentNode.getPid());
if (null != currentNode) {
if (newNodes.contains(currentNode)) break;
newNodes.add(currentNode);
}
} while (!"".equals(currentNode.getPid()));
}
}
return newNodes;
}