一般树数据的写法都是 id 对应 pid 来定义的,就像这样
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Tree implements Serializable {
/**
* 主键
*/
private Long id;
/**
* 文件夹或者文件名称
*/
private String name;
/**
* 全路径,或则部分路径,自己决定
*/
private String path;
/**
* 上级ID
*/
private Long pid;
}
如果有另外一种需求:要求实现一个无级限的功能,那我们需要把它转换一下
首先要定一个树结点,用来被所有树结构继承
@Getter
@Setter
public class TreeNode<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private Long id;
/**
* 上级ID
*/
private Long pid;
/**
* 子节点列表
*/
private List<T> children = new ArrayList<>();
}
public class Tree extends TreeNode<Tree> implements Serializable
再写一个实现转换的工具类
public class TreeUtils {
/**
* 构建树节点
*/
public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
List<T> result = new ArrayList<>();
//list转map
Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
for(T treeNode : treeNodes){
nodeMap.put(treeNode.getId(), treeNode);
}
for(T node : nodeMap.values()) {
T parent = nodeMap.get(node.getPid());
if(parent != null && !(node.getId().equals(parent.getId()))){
parent.getChildren().add(node);
continue;
}
result.add(node);
}
return result;
}
}
最后只要调用输出子节点列表
List<Tree> build = TreeUtils.build(list);
for (Tree tree : build) {
for (Tree tree1 : tree.getChildren()) {
for (Tree tree2 : tree1.getChildren()) {
}
}
}