list对象转成树结构
时间: 2023-07-22 16:34:21 浏览: 134
将List对象转成树结构,可以将List中的元素作为树的节点,通过节点之间的父子关系构建整棵树。具体实现过程如下:
1. 定义树节点类,包括节点ID、节点名称、节点父ID、子节点列表等属性。
```
public class TreeNode {
private int id;
private String name;
private int parentId;
private List<TreeNode> children;
// ...
}
```
2. 定义转换方法,将List转成树结构。遍历List中的每一个节点,如果该节点的父ID为0,则该节点为根节点;否则,将该节点添加到其父节点的子节点列表中。
```
public List<TreeNode> listToTree(List<TreeNode> list) {
List<TreeNode> tree = new ArrayList<>();
Map<Integer, TreeNode> map = new HashMap<>();
for (TreeNode node : list) {
map.put(node.getId(), node);
}
for (TreeNode node : list) {
int parentId = node.getParentId();
if (parentId == 0) {
tree.add(node);
} else {
TreeNode parent = map.get(parentId);
if (parent != null) {
if (parent.getChildren() == null) {
parent.setChildren(new ArrayList<>());
}
parent.getChildren().add(node);
}
}
}
return tree;
}
```
3. 调用转换方法,将List转成树结构。
```
List<TreeNode> list = new ArrayList<>();
// 添加节点
List<TreeNode> tree = listToTree(list);
```
通过以上方法,我们可以将List对象转成树结构,方便进行树形结构的操作和遍历。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)