Reputation: 378
Here I want to get all the children of a parent. This is my Screen.
In This screen I want to save all the rows. For that I have created the following beans.
public class AdminComponentBean{
List<MultiAdminComponent> componentListbean;
}
Another Bean:-
public class MultiAdminComponent {
private String componentName;
private String componentIdentification;
private String componentType;
private String componentState;
private String componentUrl;
private String rowId;
private List<MultiAdminComponent> items;
}
In my service I try to retrieve all the children. But I am not able to get children of the parent.
List < MultiAdminComponent > adminComponentList = adminComponentBean.getComponentListbean();
for (MultiAdminComponent adminComponentListBean: adminComponentList) {
flag = BaseDAO.getAdminComponentDAOObject().saveParentComponentDetails(adminComponentListBean);//Here the parents will save but not the childs
for (MultiAdminComponent adminComponentchild: adminComponentListBean.getItems()) {//here I am trying to save childs
}
}
Upvotes: 0
Views: 4215
Reputation: 30809
You can write a recursive method like this:
void addChildren(MultiAdminComponent parent, List<MultiAdminComponent> children) {
if(null != parent.getItems()) {
for(MultiAdminComponent child : parent.getItems()) {
children.add(child);
addChildren(child, children);
}
}
}
And call it with an empty list, e.g.:
MultiAdminComponent parent; //parent
List<MultiAdminComponent> children = new ArrayList<>();
addChildren(parent, children);
After the method call, children
list should have all the child objects.
Upvotes: 3