继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

递归构造树

judyW
关注TA
已关注
手记 47
粉丝 11
获赞 107
@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);
    }
}


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP