根据您的评论,我假设您可以将您的A
课程更改为如下所示:
class A {
Long id;
String name;
Long parentId; // refers to another A object's id
List<A> childrenNodes = new ArrayList();
}
现在,假设您已经List<A> lstData
填充了所有数据并且想要将其转换为树,您可以使用以下代码/算法:
public List<A> convertIntoTree(List<A> lstData) {
for(A parentA : lstData) {
//setting the children nodes for parentA
for(A childA : lstData) {
if (childA.getParentId() == parentA.getId()) {
parentA.getChildrenNodes().add(childA);
}
}
}
//the main tree
List<A> lstParents = new ArrayList<A>();
//filling the tree
for(A parentA : lstData) {
//change this for your check if parent function or another rule
if (parentA.getParentId() == 0) {
lstParents.add(parentA);
}
}
return lstParents;
}