[英](Data Structure) Java LinkedList objects to Tree
我有這樣的A類:
class A {
Long id;
String name;
Long parentId; // refers to another A object's id
}
現在,我得到了A對象的列表,我想將它們全部放入PC中的“文件夾樹”之類的數據結構中,然后使用JSP在GUI上查看該樹,但我不知道如何實現。 所以,請您幫忙解決以下兩個問題:
1.如何從給定的對象列表構建“文件夾樹”? 有沒有可用的API支持?
2.如何在不使用遞歸的情況下瀏覽整個數據樹並在JSP上將其作為文件夾樹查看? (我的意思是顯示它們的最佳方法是什么)
非常感謝。
根據您的評論,我假設您可以將A
類更改為以下形式:
class A {
Long id;
String name;
Long parentId; // refers to another A object's id
List<A> childrenNodes = new ArrayList();
}
現在,假設您有一個用所有數據填充的List<A> lstData
並將其轉換為Tree,則可以使用以下代碼/算法:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.