5

I am using private TreeNode root; to create a dynamycal tree.

and I used

<p:tree value="#{bean.root}" var="node">
    <p:treeNode>
        h:outputText value="#{node}" />
    </p:treeNode>
</p:tree>

to display it in my page.

my question is how to remove the nodes that are empty (doesn't contain a child)

exemple :

node1
   child 1
   child 2
node2 
node3
  child 1

(node 2 is empty, how to remove it?)

2 Answers 2

7

You can first get all the childs looping the tree:

List<TreeNode> nodes = this.root.getChildren();

Then you can maybe do something like this:

List<TreeNode> nodes = ....
Iterator<TreeNode> i = nodes.iterator();
while (i.hasNext()) {
   TreeNode = i.next(); 
   // Use isLeaf() method to check doesn't have childs.
   i.remove();
}

It would be the correct version of the next code because I guess you can't remove collection elements in a loop.

for (TreeNode treeNode : nodes) {
   if(treeNode.isLeaf()){
       TreeNode parent = treeNode.getParent();
       parent.getChildren().remove(treeNode);
   }
}

Hope it helps.

Regards.

2
0

I used this code

dropNode.getParent().getChildren().removeIf(n -> n==dropNode);

Not the answer you're looking for? Browse other questions tagged or ask your own question.