NodeTreeifyVO.class
@Data
public class NodeTreeifyVO {
/**
* 节点id
*/
private Long id;
/**
* 节点名称
*/
private String nodeName;
/**
* 上级id,为0时为顶级节点
*/
private Long parentId;
/**
* 层级
*/
private String path;
/**
* 排序
*/
private Integer sort;
/**
* 节点描述
*/
private String remark;
/**
* 节点类型
*/
private Integer nodeType;
/**
* 子节点
*/
private List<NodeTreeifyVO> childNodes;
}
/**
* 构建节点树
*
* @param nodeList 节点列表
* @return 节点树
*/
public static List<NodeTreeifyVO> buildNodeTree(List<NodeTreeifyVO> nodeList) {
Set<Long> nodeIds = nodeList.stream().map(NodeTreeifyVO::getId).collect(Collectors.toSet());
List<NodeTreeifyVO> treeList = nodeList.stream()
// 过滤出顶级节点
.filter(node -> !nodeIds.contains(node.getParentId()))
// 构建顶级节点的子节点
.peek(node -> buildChild(node, nodeList))
.collect(Collectors.toList());
// 没有查询到节点则返回原数据
if (CollectionUtils.isEmpty(treeList)) {
treeList = nodeList;
}
// 最外层节点排序
treeList.sort(Comparator.comparing(NodeTreeifyVO::getPath)
.thenComparing(NodeTreeifyVO::getSort)
.thenComparing(NodeTreeifyVO::getId));
return treeList;
}
/**
* 构建子节点
*
* @param parent
* @param list
*/
public static void buildChild(NodeTreeifyVO parent, List<NodeTreeifyVO> list) {
// 得到子节点列表
List<NodeTreeifyVO> childList = getChildList(parent.getId(), list);
parent.setChildNodes(childList);
// 递归构建子节点
childList.stream().filter(node -> node.getParentId().equals(parent.getId()))
.forEach(node -> buildChild(node, list));
}
/**
* 得到子节点列表
*
* @param pid 父节点id
* @param list
* @return
*/
public static List<NodeTreeifyVO> getChildList(Long pid, List<NodeTreeifyVO> list) {
return list.stream().filter(node -> node.getParentId().equals(pid))
.sorted(Comparator.comparing(NodeTreeifyVO::getPath)
.thenComparing(NodeTreeifyVO::getSort)
.thenComparing(NodeTreeifyVO::getId)).collect(Collectors.toList());
}
/**
* 展开节点树
*
* @param nodes 节点树
* @return
*/
private static List<NodeTreeifyVO> tileTreeNodes(List<NodeTreeifyVO> nodes) {
for (int i = nodes.size() - 1; i >= 0; i--) {
NodeTreeifyVO node = nodes.get(i);
if (!CollectionUtils.isEmpty(node.getChildNodes())) {
nodes.addAll(tileTreeNodes(node.getChildNodes()));
}
node.setChildNodes(null);
}
return nodes;
}