Convert hierarchical list to a flat list in java

前端 未结 4 566
悲哀的现实
悲哀的现实 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:43

    If you use Java 8, just add this method to the Member class:

    public Stream streamAll(){
        if(getChildren() == null){
            return Stream.of(this);
        }
        return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Member::streamAll));
    }
    

    Alternatively, you can remove the null check if you always initialize children to an empty list :

    public Stream streamAll(){
        return Stream.concat(Stream.of(this), getChildren().stream().flatMap(Member::streamAll));
    }
    

    Then to get the flat list:

    List convertedList = memberList.stream()
                                           .flatMap(Member::streamAll)
                                           .collect(Collectors.toList());
    

提交回复
热议问题