ToB企服应用市场:ToB评测及商务社交产业平台
标题:
组织树查询-Jvava实现(递归)
[打印本页]
作者:
十念
时间:
2023-4-19 13:11
标题:
组织树查询-Jvava实现(递归)
1.首先查询出组织机构
就是一个简单的查询
List<Dept> deptList = mapper.getDeptList();
Map<Long, OrgNode> nodeMap = new HashMap<>();
List<Long> rootIds = new ArrayList<>();
for (Dept dept : deptList) {
Long deptId = dept.getDeptId();
String name = dept.getDeptName();
Long parentId = dept.getParentId();
OrgNode node = nodeMap.computeIfAbsent(deptId, OrgNode::new);
node.setId(deptId);
node.setLabel(name);
node.setParentId(parentId);
if (parentId == 0) {
rootIds.add(deptId);
} else {
OrgNode parent = nodeMap.computeIfAbsent(parentId, OrgNode::new);
parent.getChildren().add(node);
}
}
// 3. 输出组织机构
List<OrgNode> orgList = new ArrayList<>();
for (long rootId : rootIds) {
orgList.add(nodeMap.get(rootId));
}
List<Map<String, Object>> result = dfs2(orgList);
复制代码
2.def2方法,只查询两级
业务需要
/**
* 只查询两级
* @param nodes
* @return
*/
private static List<Map<String, Object>> dfs2(List<OrgNode> nodes) {
List<Map<String, Object>> result = new ArrayList<>();
for (OrgNode node : nodes) {
Map<String, Object> map = new HashMap<>();
map.put("id", node.getId());
map.put("label", node.getLabel());
map.put("parentId", node.getParentId());
List<OrgNode> children = node.getChildren();
if (children != null && !children.isEmpty()){
List<OrgNode> collect = children.stream().peek(s -> s.setChildren(null)).collect(Collectors.toList());
map.put("children", collect);
}
result.add(map);
}
return result;
}
复制代码
效果
查询所有级别递归查询
/**
* 查询所有组织树
* @param nodes
* @return
*/
private static List<Map<String, Object>> dfs(List<OrgNode> nodes) {
List<Map<String, Object>> result = new ArrayList<>();
for (OrgNode node : nodes) {
Map<String, Object> map = new HashMap<>();
map.put("id", node.getId());
map.put("label", node.getLabel());
map.put("parentId", node.getParentId());
List<OrgNode> children = node.getChildren();
if (children != null && !children.isEmpty()) {
map.put("children", dfs(children));
}
result.add(map);
}
return result;
}
复制代码
3.前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>树形控件</title>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
</head>
<body>
<el-tree
:data="data"
show-checkbox
default-expand-all
node-key="id"
ref="tree"
highlight-current
:props="defaultProps"
@check-change="handleCheckChange"
:indent="20"
>
</el-tree>
<el-button @click="getCheckedNodes">通过 node 获取</el-button>
</body>
</html>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4