Java's method reference syntax offers a concise and readable way to refer to methods. In the given example, the method reference System.out::println is used as an argument to the forEach method.
Understanding the Method Reference
The method reference System.out::println signifies that the println method should be invoked using the object referred to by System.out. In this case, System.out is a static member of the System class and represents the standard output stream.
Lambda Expression Equivalent
An equivalent lambda expression for System.out::println would be:
<code class="java">o -> System.out.println(o)</code>
This lambda expression evaluates System.out first, capturing the evaluated value, and then creates a lambda function. This lambda function takes an argument o and invokes the println method on the captured System.out object, printing the value of o to the standard output.
Exact Equivalent Lambda Expression
However, it's worth noting that the exact equivalent of System.out::println would require the following steps:
Storing the evaluated System.out object in a variable:
<code class="java">PrintStream p = Objects.requireNonNull(System.out);</code>
Using the stored variable in the lambda expression:
<code class="java">numbers.forEach(o -> p.println(o));</code>
This exact equivalent ensures that any changes to System.out do not affect the lambda expression's behavior.
The above is the detailed content of What is the Lambda Expression Equivalent of System.out::println?. For more information, please follow other related articles on the PHP Chinese website!