Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
How to remove child nodes from parent?
Hi,
I'm trying to remove child nodes from a parent node. First I tried
tree.removeItem(myParent)
, but that only seems to remove the parent, not the underlying child nodes. Is this correct behavior?
Next I tried something like:
if (tree.hasChildren(MyParent) {
for (Object obj : tree.getChildren(MyParent)) {
if (obj instanceof MyChild) {
tree.removeItem(obj);
}
}
}
However this doesn´t seem to work either; only the first child is being removed!?
What am I doing wrong here?
Regards,
Gerard
Hi Gerard,
looks like a bug to me. Please see https://github.com/vaadin/framework/issues/7984 .
You're good to report bugs there yourself if you're certain you encountered one.
Best+Thanks,
--Enver
Hello Gerard,
if (ttable.hasChildren(parentId)) {
ArrayList<Object> keys = new ArrayList<>();
for (Object i :
ttable.getChildren(parentId)){
keys.add(i);
if (ttable.hasChildren(i)) {
keys.addAll(ttable.getChildren(i));
}
}
for (Object i : keys) {
ttable.removeItem(i);
}
}
Most likely simpler solution exists, but hopefully this will also work for you : )
Regards,
Anastasia
This happens because you're iterating over the same collection that is being modified (indirectly through removeItem).
An even simpler solution would be to iterate over a copy instead:
if (tree.hasChildren(MyParent) {
for (Object obj : new ArrayList(tree.getChildren(MyParent))) {
if (obj instanceof MyChild) {
tree.removeItem(obj);
}
}
}
Ah, true.
I had this idea in mind, but basically made the same mistake.
Closing bug.
Hi,
Thanks for your help, I was already afraid of making exactly just this mistake!
Regards,
Gerard