@Data
@NoArgsConstructor
public class Foo {
private Integer id;
private Integer parentId;
private List<Foo> children;
public Foo(Integer id, Integer parentId) {
this.id = id;
this.parentId = parentId;
}
}
public class FooTest {
public static Foo BuildTree(List<Foo> fooList){
Foo root = new Foo();
fooList.forEach(item ->{
if(item.getParentId() == 0){
root.setId(item.getId());
root.setParentId(0);
root.setChildren(getChild(item.getId(),fooList));
}
});
return root;
}
private static List<Foo> getChild(Integer id, List<Foo> fooList) {
List<Foo> child = Lists.newArrayList();
fooList.forEach(item->{
if(item.getParentId() == id){
child.add(item);
}
});
child.forEach(item ->{
item.setChildren(getChild(item.getId(),fooList));
});
if(CollectionUtils.isEmpty(child)){
return new ArrayList<Foo>();
}
return child;
}
public static void main(String[] args) {
List<Foo> list = new ArrayList<>();
list.add(new Foo(1,0));
list.add(new Foo(2,1));
list.add(new Foo(3,1));
list.add(new Foo(4,1));
list.add(new Foo(5,2));
list.add(new Foo(6,3));
Foo foo = BuildTree(list);
System.out.println(foo);
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦