为了账号安全,请及时绑定邮箱和手机立即绑定

递归构造树

标签:
Java
@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 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
11
获赞与收藏
107

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消