简体   繁体   中英

(Data Structure) Java LinkedList objects to Tree

I have a class A like this:

class A {
    Long id;
    String name;
    Long parentId; // refers to another A object's id
}  

Now I get the list of A objects, and I want to put them all to a data-structure like "folder tree" in PC, and then view that tree on GUI using JSP but I do not know how to implement this. So could you please help on these 2 problems:
1. How to build a "folder tree" from a given list of objects? Is there any available API support this?
2. How can we browse that whole data tree and view it on JSP as folder tree without using recursion? (I mean what is the best way to display them)
Thank you so much.

Based on your comments, I assume that you can change your A class to look like this:

class A {
    Long id;
    String name;
    Long parentId; // refers to another A object's id
    List<A> childrenNodes = new ArrayList();
}

Now, assuming you have a List<A> lstData filled with all the data and you want to convert it into a Tree, you can use the following code/algorithm:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM