@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);
}
}
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦