Convert hierarchical list to a flat list in java

前端 未结 4 570
悲哀的现实
悲哀的现实 2021-01-20 17:10

I have a hierarchical list like below and I want to convert it to a flat list.

I have wrote a method called convertToFlatList

4条回答
  •  执念已碎
    2021-01-20 17:52

    If a Member has children, you correctly add the children to the flattened list, but miss the Member itself. Just move the addition of the member outside of the else block add you should be fine:

    private static List 
    convertToFlatList(List memberList, List flatList)
    {
        for (Member member : memberList)
        {
            // Always add the member to flatList
            flatList.add(memeber);
    
            // If it has children, add them toore
            if (member.getChildren() != null)
            {
                convertToFlatList(member.getChildren(), flatList);
            }
        }
        return flatList;
    }
    

提交回复
热议问题