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
?
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.
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.
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.
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.
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 useo -> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With