java怎么将批量组织机构全路径fullpath 生成树形结构
时间: 2024-02-02 19:04:56 浏览: 94
要将批量组织机构全路径fullpath生成树形结构,可以使用递归算法和Map数据结构。
首先,将fullpath分割成每个组织机构的名称,然后逐级构建Map数据结构,最后将Map转换为树形结构即可。
以下是Java代码示例:
```java
public class OrgTreeBuilder {
public static OrgNode buildTree(List<String> fullPaths) {
// 构建Map,key为组织机构名称,value为子节点Map
Map<String, Map<String, Object>> map = new HashMap<>();
for (String fullPath : fullPaths) {
String[] orgNames = fullPath.split("/");
Map<String, Map<String, Object>> curMap = map;
for (int i = 0; i < orgNames.length; i++) {
String orgName = orgNames[i];
if (!curMap.containsKey(orgName)) {
Map<String, Object> childMap = new HashMap<>();
curMap.put(orgName, childMap);
}
curMap = (Map<String, Map<String, Object>>) curMap.get(orgName);
}
}
// 转换为树形结构
OrgNode root = new OrgNode("root");
buildTree(root, map);
return root;
}
private static void buildTree(OrgNode parent, Map<String, Map<String, Object>> map) {
for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) {
String orgName = entry.getKey();
OrgNode node = new OrgNode(orgName);
parent.addChild(node);
buildTree(node, (Map<String, Map<String, Object>>) entry.getValue());
}
}
}
public class OrgNode {
private String name;
private List<OrgNode> children = new ArrayList<>();
public OrgNode(String name) {
this.name = name;
}
public void addChild(OrgNode child) {
children.add(child);
}
// getter and setter
}
```
使用示例:
```java
List<String> fullPaths = Arrays.asList(
"a/b/c",
"a/b/d",
"a/e/f",
"g/h/i/j"
);
OrgNode root = OrgTreeBuilder.buildTree(fullPaths);
// 遍历树形结构
traverse(root, 0);
private static void traverse(OrgNode node, int level) {
System.out.println(StringUtils.repeat("-", level) + node.getName());
for (OrgNode child : node.getChildren()) {
traverse(child, level + 1);
}
}
```
输出结果:
```
-root
--a
---b
----c
----d
---e
----f
--g
---h
----i
-----j
```
阅读全文