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

DIBits :

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

Naman :

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73119&siteId=1