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?
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
When any function is called from main(), the memory is allocated to it on the stack. A recursive function calls itself, the memory for the called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call.
Streams in Java provide a functional approach to process a collection of objects. Stream. java provides different methods to process list elements, map(), flatMap(), filter(), sorted() etc, each of which takes a functional interface type as an argument.
Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances. The point to take home is that sequential streams are no faster than loops.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With