How to get all the children of the parent and their children using recursion

refference.

Here I want to get the child of the parent and their children. This is my screen.

In this window I want to save all the lines. For this, I created a beans file.

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 am trying to restore all children. But I can not get the 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

          }
 }
0
source share
1 answer

You can write a recursive method as follows:

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, for example:

MultiAdminComponent parent; //parent
List<MultiAdminComponent> children = new ArrayList<>();
addChildren(parent, children);

After calling the method, the list childrenshould have all the child objects.

+2
source

Source: https://habr.com/ru/post/1683523/


All Articles