实体
@Data
public class SysCategoryTree {private static final long serialVersionUID = 1L;private String id;/** 父级节点 */private String pid;/** 类型名称 */private String name;/** 类型编码 */private String code;@TableField(exist = false)private List<SysCategoryTree> nodes;public SysCategoryTree() {// 默认使用哈希表nodes = new ArrayList<>();}
}
构建树形结构
public static List<SysCategoryTree> buildSysCategoryTree(List<SysCategoryTree> node) {List<SysCategoryTree> res = new ArrayList<>();Map<String, SysCategoryTree> map = new HashMap<>();node.forEach(n -> map.put(n.getId(), n));node.forEach(n -> {//表示不是根目录if (n.getPid() != null) {if (n.getPid().equals("0")) {res.add(n);} else {//get当前父级节点SysCategoryTree tree = map.get(n.getPid());//根据父节点未查询到上级,代表错误数据,删除if (tree != null) {//将当前对象添加到当前父级节点的子级节点属性中tree.getNodes().add(n);}}}});return res;}
根据节点id获取该节点下所有数据
public List<SysCategoryTree> getNodeTree(List<SysCategoryTree> resList,String pid){List<SysCategoryTree> sysCategoryTree = new ArrayList<>();for (int i = 0; i < resList.size(); i++) {String id = resList.get(i).getId();List<SysCategoryTree> nodes = resList.get(i).getNodes();if(id.equals(pid)){sysCategoryTree.add(resList.get(i));}}if(CollectionUtils.isEmpty(sysCategoryTree)){for (SysCategoryTree sysCategoryTree1:resList){if(CollectionUtils.isNotEmpty(sysCategoryTree1.getNodes())){if(CollectionUtils.isNotEmpty(getNodeTree(sysCategoryTree1.getNodes(),pid))){return getNodeTree(sysCategoryTree1.getNodes(),pid);}else{getNodeTree(sysCategoryTree1.getNodes(),pid);}}}}return sysCategoryTree;}