简体   繁体   中英

How does recursion work with Java 8 Stream?

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?

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

ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM