Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent lambda expression for System.out::println

I stumbled upon the following Java code which is using a method reference for System.out.println:

class SomeClass {     public static void main(String[] args) {            List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9);            numbers.forEach(System.out::println);         }     } } 

What is the equivalent lambda expression for System.out::println?

like image 603
Steve Avatar asked Jan 19 '15 11:01

Steve


People also ask

What is the exact equivalent lambda expression?

println(o) to achieve the same as the method reference, but this lambda expression will evaluate System. out each time the method will be called. So an exact equivalent would be: PrintStream p = Objects. requireNonNull(System.

What is System Out :: Println?

In Java, System. out. println() is a statement which prints the argument passed to it. The println() method display results on the monitor. Usually, a method is invoked by objectname.

What is the lambda expression in Java?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Which can be used instead of lambda expression?

How to replace lambda expression with method reference in Java 8. If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference.


1 Answers

The method reference System.out::println will evaluate System.out first, then create the equivalent of a lambda expression which captures the evaluated value. Usually, you would use
o -> System.out.println(o) to achieve the same as the method reference, but this lambda expression will evaluate System.out each time the method will be called.

So an exact equivalent would be:

PrintStream p = Objects.requireNonNull(System.out); numbers.forEach(o -> p.println(o)); 

which will make a difference if someone invokes System.setOut(…); in-between.

like image 112
Holger Avatar answered Oct 09 '22 04:10

Holger