Reputation: 485
I have below Tree
class with the following attributes and their getters and setters.
public class Tree {
private String name, address;
private List<Tree> child;
}
I am iterating a Tree
and comparing the name with a list of valid names. If the name is not valid, I have to remove that specific Tree
node from the main Tree
. However, I don't know how to implement the remove functionality.
private void validateTree(Tree tree) {
if (tree.getChild() != null && !tree.getChild().isEmpty()) {
for(Tree node:tree.getChild()){
if(list.contains(node.getName())){ // String elements in list
validateTree(tree); // validate the subtree
} else {
// Here I have to remove the child node from the Tree.
}
}
}
}
Upvotes: 0
Views: 346
Reputation: 5954
The safe way to remove an element from a collection is using iterator. In your case it may look like this:
List<Tree> children = tree.getChild();
for (Iterator<Tree> iterator = children.iterator(); iterator.hasNext();) {
Tree node = iterator.next();
if (list.contains(node.getName())){ // String elements in list
validateTree(tree); //OK
} else {
iterator.remove();
}
}
Upvotes: 1
Reputation: 3093
The easiest way is to add a removeChild()
method in your Tree
:
public class Tree {
List<Tree> child;
public void removeChild(Tree tree) {
child.remove(tree);
}
}
In your validation method you can use it:
if (validNodes.contains(node.getName())) {
validateTree(tree);
} else {
tree.removeChild(node);
}
However, you should always be very suspicious when you are changing a collection that you are looping over. I would strongly suggest to leave the original Tree
as is, and create a second, valid, Tree
that only contains the valid nodes.
Upvotes: 2