package org.sxkj.system.util; import org.sxkj.system.entity.DictBiz; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TreeBuilder { /** * 构建树形结构 * @param list 原始数据列表 * @return 树形结构列表 */ public static List buildTree(List list) { // 用于存储id和对应的节点 Map nodeMap = new HashMap<>(); // 最终返回的树形结构 List tree = new ArrayList<>(); // 第一遍遍历:将所有节点存入map,并初始化children列表 for (DictBiz node : list) { nodeMap.put(node.getId(), node); if (node.getChildrenList() == null) { node.setChildrenList(new ArrayList<>()); } } // 第二遍遍历:建立父子关系 for (DictBiz node : list) { Long parentId = node.getParentId(); if (parentId != null && parentId != 0) { // 假设0表示顶级节点 DictBiz parent = nodeMap.get(parentId); if (parent != null) { parent.getChildrenList().add(node); } } else { // 没有父节点或父节点为0,认为是顶级节点 tree.add(node); } } return tree; } /** * 使用Stream API实现的树形结构构建 * @param list 原始数据列表 * @return 树形结构列表 */ public static List buildTreeWithStream(List list) { Map nodeMap = list.stream() .collect(Collectors.toMap(DictBiz::getId, node -> node)); List tree = new ArrayList<>(); list.forEach(node -> { Long parentId = node.getParentId(); if (parentId != null && parentId != 0) { DictBiz parent = nodeMap.get(parentId); if (parent != null) { if (parent.getChildrenList() == null) { parent.setChildrenList(new ArrayList<>()); } parent.getChildrenList().add(node); } } else { tree.add(node); } }); return tree; } }