How to Avoid nested for Loops in java to get the heirarchical data?

Tags: , , , ,



// This method will return the list of reference names, in this method I wrote the code using nested //for-loops this handle only 3 subfolders set what if there is one more subfolder and how to handle it //without for loops, OverAll I should handle it dynamically

            // Iterate the subfolders to populate the orgRefName List 
            //In this we are handling the subfolders with the use of nested for loops, How to handle //the scenario if there is one more child Subfolder dynamically

// How to solve without using additional nested for loop to get the additional for loop

//for-loops this handle only 3 subfolders set what if there is one more subfolder and how to handle it //without for loops, OverAll I should handle it dynamically

            for (OrgDetails orgDetails : orgList) {
                mainSubFolder = orgDetails.getSubfolders();
                for (OrgSubfolderDetails orgDetails2 : mainSubFolder) {
                    childSubFolder1 = orgDetails2.getSubfolders();
                    if (!childSubFolder1.isEmpty()) {
                        for (OrgSubfolderDetails orgDetails3 : childSubFolder1) {
                            childSubFolder2 = orgDetails3.getSubfolders();
                            if (!childSubFolder2.isEmpty()) {
                                for (OrgSubfolderDetails orgDetails4 : childSubFolder2) {
                                    refDetails = orgDetails4.getOrgRefDetails();
                                    if (!refDetails.isEmpty()) {
                                        for (OrgRefDetails orgDetails5 : refDetails) {
                                            RefNameList.add(orgDetails5.getRefName());
                                        }
                                    }
                                }
                            }
                        }
                    }
    
                }
            }
            
            return RefNameList;
            
        }

Answer

If you are using Java 8, streams with flatmap will help you to achieve this. Something like this https://dzone.com/articles/walking-recursive-data

If java 7 we can iterate the OrgSubfolderDetails recursively.



Source: stackoverflow