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
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