树结构实体类
/**
* @Author: DMG Cai
* @Date: 2021/2/18 13:57
*/
public class TreeEntity {
/**
* 节点名称
*/
private String title;
/**
* 节点id
*/
private Long key;
/**
* 父节点id
*/
private Long parentKey;
/**
* 排序顺序
*/
private Integer sortOrder;
/**
* 子节点集
*/
private List<TreeEntity> children;
}
转成树结构
// 根节点父id
private static final long ROOT_NODE_ID = 0;
/**
* 整理成树结构
* @author: DMG Cai at 2021/8/10 11:02
* @param treeEntityList
* @param parentKey 父id
* @param nodeFu 给node 的属性赋值 key parentKey title sortOrder 等 及其子类扩展属性
* @return:
*/
public static <T, R extends TreeEntity> List<R> buildTree(List<T> treeEntityList, Function<T, Long> parentKey, Function<T, R> nodeFu) {
return buildTree(ROOT_NODE_ID, treeEntityList, parentKey, nodeFu);
}
/**
* 整理成树结构
* @author: DMG Cai at 2021/8/10 12:03
* @param parentId 父id
* @param treeEntityList 数据集合
* @param parentKey 获取 数据的 父id值
* @param nodeFu 给node 的属性赋值 key parentKey title sortOrder 等 及其子类扩展属性
* @return:
*/
public static <T, R extends TreeEntity> List<R> buildTree(Long parentId, List<T> treeEntityList, Function<T, Long> parentKey, Function<T, R> nodeFu) {
if (parentId == null) {
throw new BusinessException("父id为空");
}
if (CollectionUtils.isEmpty(treeEntityList)) {
return Collections.emptyList();
}
return treeEntityList.stream()
.filter(te -> parentKey.apply(te).equals(parentId))
.map(te -> {
R node = nodeFu.apply(te);
List<R> rList = buildTree(node.getKey(), treeEntityList, parentKey, nodeFu);
node.setChildren(rList.isEmpty() ? null : (List<TreeEntity>) rList);
return node;
}).sorted(Comparator.comparing(TreeEntity::getSortOrder)).collect(Collectors.toList());
}
示例
// 部门实体类
public class SysDepartment {
/**
* 部门id
*/
private Long id;
/**
* 父部门id
*/
private Long parentId;
/**
* 部门代码
*/
private String departmentCode;
/**
* 部门名称
*/
private String departmentName;
/**
* 层级
*/
private Integer level;
/**
* 排序
*/
private Integer sortOrder;
}
// 将部门集合整理成树结构
private List<TreeEntity> getTreeNodes(List<SysDepartment> departmentList) {
return TreeUtils.buildTree(departmentList, SysDepartment::getParentId, department -> {
TreeEntity node = new TreeEntity();
node.setTitle(department.getDepartmentName());
node.setKey(department.getId());
node.setParentKey(department.getParentId());
node.setSortOrder(department.getSortOrder());
return node;
});
}