How does recursion work with Java 8 Stream?

后端 未结 2 1209
失恋的感觉
失恋的感觉 2020-12-30 06:29

I have a method like this where I\'m using recursion with Streams:

  private static List convertToFlatList(List memberList)
  {
          


        
相关标签:
2条回答
  • 2020-12-30 07:01

    The termination happens because for the "leafs" that don't have any children,

    Stream.concat(Stream.of(i), convertToFlatList(i.getChildren()).stream())
    

    will invoke convertToFlatList on an empty list, and applying flatMap() on an empty stream does not invoke the mapping operation.

    0 讨论(0)
  • 2020-12-30 07:14

    The recursion will end when memberList will be empty, since at this case an empty List will be returned.

    i.e. when i.getChildren() is an empty List, the recursive call convertToFlatList(i.getChildren()) will receive an empty List, so the Stream pipeline won't make another recursive call (since it has no elements to execute flatMap on), and will return an empty List.

    0 讨论(0)
提交回复
热议问题