Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Stream iterate is not working with a predicate when doing a check for even-odd

I am trying to create a Stream of even integer using Stream.iterate where I will pass a Predicate to check for even and an Unary operator.

        Stream<Integer> stream = Stream.iterate(0, s-> ((s<10) && (s%2==0)),  s-> s+1);
        stream.forEach(System.out::println);

Problem is it is just printing 0.

If I remove the even check s%2==0. It is printing number from 0-9

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        Stream<Integer> stream = Stream.iterate(0, s-> (s<10),  s-> s+1);
        stream.forEach(System.out::println);

If I remove the s<10 and just keep the s%2==0 and put a limit. Still I only get 0 as output.

        Stream<Integer> stream = Stream.iterate(0, s-> (s%2==0),  s-> s+1);
        stream.limit(10).forEach(System.out::println);

I am not able to understand where I am going wrong. I know I can achieve this with filter but the point is I am not able to identify my mistake and with Lambda I am not able to debug in eclipse.

>Solution :

Ihe second parameter is called hasNext, so if s is 1 the prdicate return false and the iteration stops.

Use:

  IntStream.range(0,10).filter(s-> s%2==0).forEach(System.out::println);

it will print:

0
2
4
6
8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading