简体   繁体   English

列表列表的递归函数

[英]Recursive function for list of lists

I have an object(of type 'Flows') which contains a list of type 'Flows'我有一个对象(类型为“Flows”),其中包含一个“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?我们如何通过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. flowsList是您要将所有流添加到的列表。

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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM