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?)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With