Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function for list of lists

I have an object(of type 'Flows') which contains a list of type 'Flows'

class Flows{
 String id;
 String sequence;
 List<Flows> listOfFlows;
}

I want to get all the elements of all the nested lists (can have any number of nested list) into a single list. How can we achieve it through recursion in java?

like image 408
Mario Avatar asked May 25 '26 19:05

Mario


1 Answers

What about something like:

void flattenFlows(Flows flows, List<Flows> flowsList)
{
    flowsList.add(flows);
    for (Flows f: flows.listOfFlows) {
        flattenFlows(f, flowsList);
    }
}

flowsList being the list you want to add all the flows to.

Edit: if it is possible for the list field to be null (as one commenter pointed out), add a null check:

void flattenFlows(Flows flows, List<Flows> flowsList)
{
    flowsList.add(flows);
    if(flow.listOfFlows!=null) {
        for (Flows f: flows.listOfFlows) {
            flattenFlows(f, flowsList);
        }
    }
}
like image 179
Stan Ostrovskii Avatar answered May 27 '26 09:05

Stan Ostrovskii