递归遍历部门树
遍历方法:
public class SysTest { /** * 构建前端所需要树结构 * * @param depts 部门列表 * @return 树结构列表 */ public List<SysDept> buildDeptTree(List<SysDept> depts) { List<SysDept> returnList = new ArrayList<SysDept>(); List<Long> tempList = new ArrayList<Long>(); for (SysDept dept : depts) { tempList.add(dept.getDeptId()); } for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext();) { SysDept dept = (SysDept) iterator.next(); // 如果是顶级节点, 遍历该父节点的所有子节点 if (!tempList.contains(dept.getParentId())) { recursionFn(depts, dept); returnList.add(dept); } } if (returnList.isEmpty()) { returnList = depts; } return returnList; } /** * 递归列表 */ private void recursionFn(List<SysDept> list, SysDept t) { // 得到子节点列表 List<SysDept> childList = getChildList(list, t); t.setChildren(childList); for (SysDept tChild : childList) { if (hasChild(list, tChild)) { recursionFn(list, tChild); } } } /** * 得到子节点列表 */ private List<SysDept> getChildList(List<SysDept> list, SysDept t) { List<SysDept> tlist = new ArrayList<SysDept>(); Iterator<SysDept> it = list.iterator(); while (it.hasNext()) { SysDept n = (SysDept) it.next(); if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) { tlist.add(n); } } return tlist; } /** * 判断是否有子节点 */ private boolean hasChild(List<SysDept> list, SysDept t) { return getChildList(list, t).size() > 0 ? true : false; } }
调用及lambda表达式处理:
public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) { List<SysDept> deptTrees = buildDeptTree(depts); return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList()); }
树的实体类:
package com.ruoyi.common.core.domain; import java.io.Serializable; import java.util.List; import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonInclude; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysMenu; /** * Treeselect树结构实体类 * * @author ruoyi */ public class TreeSelect implements Serializable { private static final long serialVersionUID = 1L; /** 节点ID */ private Long id; /** 节点名称 */ private String label; /** 子节点 */ @JsonInclude(JsonInclude.Include.NON_EMPTY) private List<TreeSelect> children; public TreeSelect() { } public TreeSelect(SysDept dept) { this.id = dept.getDeptId(); this.label = dept.getDeptName(); this.children = dept.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList()); } public TreeSelect(SysMenu menu) { this.id = menu.getMenuId(); this.label = menu.getMenuName(); this.children = menu.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList()); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public List<TreeSelect> getChildren() { return children; } public void setChildren(List<TreeSelect> children) { this.children = children; } }