Java使用Primefaces TreeNode创建具有唯一节点ID的树

时间:2016-03-18 11:36:55

标签: java jsf primefaces treenode

我搜索过类似的东西,但遗憾的是我找不到与我的问题相关的任何内容。

所以我尝试使用primefaces TreeNode类(org.primefaces.model.TreeNode)动态创建树

问题是,我无法弄清楚如何正确实现算法,因此即使ID是唯一ID,我也可以创建所有节点。

我使用的实体:

  • id(唯一,整数)
  • parentId(指向id,Integer)可以为null。 (然后它在根下)
  • name(实际节点名称,字符串)

这就是我目前创建树的方式:

    public TreeNode createTree() {

    TreeNode root = new CheckboxTreeNode("root", null);

    List<Entity> entities = dao.getEntities();

    if (entities != null) {

        Map<Integer, TreeNode> treeNodeMap = new HashMap<Integer, TreeNode>(); 

        for (Entity entity : entities) {
            treeNodeMap.put(entity.getId(), new CheckboxTreeNode(Entity));
        }

        Set<Integer> ids = treeNodeMap.keySet();

        for (Integer id : ids) {    

            TreeNode node = treeNodeMap.get(id);
            Entity temp = (Entity) node.getData();

            if(temp.getParentId() == null) { 
                node = new CheckboxTreeNode(temp, root); 
            } 
            else {
                TreeNode parentNode = treeNodeMap.get(temp.getParentId());
                node = new CheckboxTreeNode(temp, parentNode);
            }
            treeNodeMap.put(temp.getId(), node);
        }
    }
    else {
        //TODO
        //Exception handling
    }
    return root;
}

此代码工作正常,但正如我试图提到的,它没有涵盖唯一ID的问题。如果此节点的ID大于迭代中的下一个ID,则不会添加节点。

我想要这个假人:

public List<Entity> dummyData() {
    List<Entity> entities = new ArrayList<Entity>();

    /*
     * Constructor of Entity:
     * ID
     * Parent ID
     * Name
     * */

    entities.add(new Entity(1, null, "01"));
        entities.add(new Entity(5, 1, "01-01"));
        entities.add(new Entity(108, 1, "01-02"));
        entities.add(new Entity(3, 1, "01-03"));

    entities.add(new Entity(2, null, "02"));
        entities.add(new Entity(6, 2, "02-01"));
        entities.add(new Entity(7, 2, "02-02"));
            entities.add(new Entity(77, 7, "02-02-01"));
            entities.add(new Entity(66, 7, "02-02-02"));
                entities.add(new Entity(22, 66, "02-02-02-01"));
                entities.add(new Entity(57, 66, "02-02-02-02"));
                entities.add(new Entity(180, 66, "02-02-02-03"));
            entities.add(new Entity(107, 7, "02-02-03"));
        entities.add(new Entity(8, 2, "02-03"));

    return entities;
}

导致:

01
----01-01
----01-02
----01-03
02
----02-01
----02-02
    ----02-02-01
    ----02-02-02
        ----02-02-02-01
        ----02-02-02-02
        ----02-02-02-03
    ----02-02-03
----02-03   

但它导致:

01
----01-03
----01-01
----01-02
02
----02-01
----02-02
    ----02-02-02
    ----02-02-01
        ----02-02-02-03
        ----02-02-02-02 <- MISSING
        ----02-02-02-03 <- MISSING
    ----02-02-03
----02-03

对于如何解决这个问题有什么建议吗?

0 个答案:

没有答案