@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,阅读手记