简体   繁体   English

(数据结构)Java LinkedList对象到Tree

[英](Data Structure) Java LinkedList objects to Tree

I have a class A like this: 我有这样的A类:

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. 现在,我得到了A对象的列表,我想将它们全部放入PC中的“文件夹树”之类的数据结构中,然后使用JSP在GUI上查看该树,但我不知道如何实现。 So could you please help on these 2 problems: 所以,请您帮忙解决以下两个问题:
1. How to build a "folder tree" from a given list of objects? 1.如何从给定的对象列表构建“文件夹树”? Is there any available API support this? 有没有可用的API支持?
2. How can we browse that whole data tree and view it on JSP as folder tree without using recursion? 2.如何在不使用递归的情况下浏览整个数据树并在JSP上将其作为文件夹树查看? (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: 根据您的评论,我假设您可以将A类更改为以下形式:

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: 现在,假设您有一个用所有数据填充的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.

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