Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
Sandeepa Avatar asked Jan 03 '19 07:01

Sandeepa


People also ask

How does Java 8 streams work internally?

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.

How does recursive function work in Java?

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.

Does streams in Java 8 support functional programming?

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.

Is Java 8 stream faster than for loop?

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.


1 Answers

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.

like image 93
Eran Avatar answered Oct 18 '22 23:10

Eran