2

What is the best way to transform a while loop like the one below to the functional stream if you don't know the exact number of iterations?

int i = 10;
while (i > 1) {
    System.out.println(i);
    i--;
}

I came up with something like this, but I want to remove the limit and stop iteration with something like a predicate condition

Stream.iterate(10, n -> n - 1).filter(n -> n > 1).limit(9).forEach(System.out::println);
marekmuratow
  • 394
  • 2
  • 13
  • 2
    just a side note, to match the logic of your while loop, you should have used `forEachOrdered` and not `forEach` – Eugene Oct 02 '18 at 14:33

1 Answers1

3

takeWhile, since java-9 though:

 Stream.iterate(10, n -> n - 1) 
       .takeWhile(i -> i > 1)
       .forEach(System.out::println);

See a back port for java-8 here also.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Thanks for the info. I am trying to do this in java 8. – marekmuratow Oct 02 '18 at 13:43
  • I can see it, but it doesn't look like a good refactoring to make the code more readable. – marekmuratow Oct 02 '18 at 13:46
  • 1
    @Mark well, if you need this by a `Predicate`, you can't do it otherwise. `Stream::iterate` also has a method that acts like a for loop (and thus will work for your case) - but since 9 also... – Eugene Oct 02 '18 at 13:48