How does recursion work with Java 8 Stream?

Sandeepa :

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

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

Lets say a Member class has a children list of members that is always initialized to an empty list. Here what I'm doing is converting the hierarchical list of members to a flat list. I understand that part. What I don't understand is how recursion works here.

In recursion, it's terminated when certain conditions are met. But here I'm not giving any condition for terminating intentionally. So how does the termination part work here?

Eran :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35771&siteId=1