Can't use System.out.println on stream for each
I am studying a flat map and want to print an endless sequence integers
.
However, when I try to compile the program, it fails when System.out.println
:
public class Test{
public static void main(String[] args) {
Stream.of("").flatMap(x -> Stream.iterate(1, i -> i + 1)).forEach(System.out.println);
}
}
Can someone help me with this and let me know how I can do this and if possible please check my code to print endless sequence integers
for problems.
source to share
You must transfer Consumer
to forEach
.
You can use a lambda expression:
Stream.of("").flatMap(x -> Stream.iterate(1, i -> i + 1)).forEach(i -> System.out.println (i));
or method link:
Stream.of("").flatMap(x -> Stream.iterate(1, i -> i + 1)).forEach(System.out::println);
PS, I don't know why you create an initial single element Stream
and then use flatMap
instead of just creating an infinite Stream
and running forEach
on it:
Stream.iterate(1, i -> i + 1).forEach(System.out::println);
source to share
You have to really watch out for infinite streams and flatmap
since they are eagerly computed btw it is not very trivial to understand:
Stream.of("")
.flatMap(x -> Stream.iterate(1, i -> i + 1))
.limit(1) // added this one
.forEach(System.out::println);
This will print 1
and never finish - limit
doesn't work here .
source to share