Difficulties of recursion with Streams

Remi Forax forax at univ-mlv.fr
Fri Nov 14 10:42:18 UTC 2025


Hi David, 
You can always transform an imperative code to a stream by pushing the element through a consumer. 
Internally, a stream uses a push iterator (see Spliterator.tryAdvance(consumer)). 

As a silly example, this is a way to write fibonacci (the recursive form) with a stream right in the middle. 

static void fibo ( int n , IntConsumer consumer ) { 
if ( n < 2 ) { 
consumer .accept( n ); 
return ; 
} 
var result = Stream . of ( "" ) 
.mapMultiToInt(( _ , consumer2 ) -> { 
fibo ( n - 1 , consumer2 ); 
fibo ( n - 2 , consumer2 ); 
}) 
.sum(); 
consumer .accept( result ); 
} 

static void main () { 
fibo ( 7 , IO :: println ); 
} 

Here, I use mapMulti() to convert the imperative code to a Stream 
(there is no factory method on Stream that takes a consumer of consumer). 

If you also want to short-circuit, you can use a gatherer instead of mapMulti but short-circuiting the recursive code will require to use an exception as control flow (it will not be pretty). 

regards, 
Rémi 

> From: "David Alayachew" <davidalayachew at gmail.com>
> To: "core-libs-dev" <core-libs-dev at openjdk.org>
> Sent: Tuesday, November 11, 2025 4:36:29 AM
> Subject: Difficulties of recursion with Streams

> Hello [ mailto:core-libs-dev at openjdk.org | @core-libs-dev ] ,

> When working with streams, I often run into situations where I have to "demote"
> back to imperative code because I am trying to solve a problem best solved by
> recursion.

> Consider the common use case of cycling through permutations to find all
> permutations that satisfy some condition. With recursion, the answer is
> incredibly simple -- just grab an element from the set, then call the recursive
> method with a copy of the set minus the grabbed element. Once you reach the
> empty set, you've reached your terminal condition.

> Use cases like that are not only incredibly common, but usually, embarrassingly
> parallel. The example above of cycling through permutations is only a few lines
> of imperative code, but I struggle to imagine how I would do this with Streams.

> I guess let me start by asking -- are there any good ways currently to
> accomplish the above permutation example with Streams? And if not, should there
> be?

> Thank you for your time and consideration.
> David Alayachew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20251114/55e02c11/attachment-0001.htm>


More information about the core-libs-dev mailing list