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?
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With