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.

+3


source to share


4 answers


Plain:

System.out.println

      

not a method reference. You need



System.out::println

      

instead of this. See here for a reading. The point is that something flatMap()

awaits you that he can "call". And System.out.println

does not denote what might be called. Just invalid syntax, so!

+6


source


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

      

+3


source


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 .

+3


source


System.out::println //is the valid method reference. 

      

0


source







All Articles