Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to stop Stream.iterate() with a predicate? [duplicate]

In the web I found only one way to stop the iterate method. By using the limit() function. But that iterates a concreate ammount of loops. I want use for the halt a predicate.

...
Stream.iterate(0, i -> i*2).while(i -> i < MAX)
...

Is there a way to do it with Streams?

Update 1 : Java 8 is used

like image 649
DIBits Avatar asked Dec 24 '22 01:12

DIBits


1 Answers

Using Java-9 or above, one way is to use Stream.takeWhile as:

Stream.iterate(1, i -> i * 2) // notice identity value in seed
      .takeWhile(i -> i < MAX)

Another alternative is to use Stream.iterate

Stream.iterate(1, i -> i < MAX, i -> i * 2)
like image 71
Naman Avatar answered May 08 '23 09:05

Naman