时间复杂度3n,采用Stream流循环遍历三次
1.TreeModel 实体类
public class TreeModel {
/**
* 名称
**/
private String name;
/**
* id
**/
private Long id;
/**
* 父级id
**/
private Long parentId;
/**
* 子级列表
**/
private List<TreeModel> children;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public List<TreeModel> getChildren() {
return children;
}
public void setChildren(List<TreeModel> children) {
this.children = children;
}
public TreeModel(Long id, String name, Long parentId) {
this.name = name;
this.id = id;
this.parentId = parentId;
}
public TreeModel(Long id, String name) {
this.name = name;
this.id = id;
this.parentId = null;
}
@Override
public String toString() {
return "TreeModel{" +
"name='" + name + '\'' +
", id=" + id +
", parentId=" + parentId +
", children=" + children +
'}';
}
}
2.测试方法
@Test
public void test(){
List<TreeModel> list = new LinkedList<>();
list.add(new TreeModel(1L,"测试1",0L));
list.add(new TreeModel(2L,"测试2",0L));
list.add(new TreeModel(3L,"测试3",1L));
list.add(new TreeModel(4L,"测试4",1L));
list.add(new TreeModel(5L,"测试5",3L));
list.add(new TreeModel(6L,"测试6",5L));
list.add(new TreeModel(7L,"测试7",8L));
list.add(new TreeModel(8L,"测试8",0L));
//本次循环,是为了找到所有父code下面的所有的子节点
Map<Long, List<TreeModel>> listInfoParenMap = list.stream().collect(Collectors.groupingBy(TreeModel::getParentId));
//本次循环,是为了给所有的节点,设置子节点
//对象赋值时复制的是引用地址,所以list以及listInfoParenMap都会在赋值过程中变化
list.forEach(cityInfo -> cityInfo.setChildren(listInfoParenMap.get(cityInfo.getId())));
//是为了找到所有的根节点
List<TreeModel> collect = list.stream().filter(cityInfo -> cityInfo.getParentId()==0).collect(Collectors.toList());
System.out.println(collect);
}
3.debug流程分析
第一次遍历
listInfoParenMap子节点的子节点无值
第二次遍历
list被改变,并且已经形成Tree,同时listInfoParenMap也被改变形成了Tree
第三次遍历
仅拿到父Id为0数据