How does recursion work with Java 8 Stream?

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.


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.