Convert hierarchical list to a flat list in java

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

    Do this by using java-8 flatMap and recursion

    Change convertToFlatList method to take only one argument (i,e List)

    If getChildren() is not null, then do the recursion or else return the current object

    private static List convertToFlatList(List memberList)
      {
           return memberList.stream().flatMap(i->{
              if(Objects.nonNull(i.getChildren())) {
                 return Stream.concat(Stream.of(i), convertToFlatList(i.getChildren()).stream());
              }
              return Stream.of(i);
    
          }).collect(Collectors.toList());
    
      }   
    

    Output :

    [1, 2, 3, 4, 5, 6, 7]
    

提交回复
热议问题