Home  >  Article  >  Java  >  What is the Lambda Expression Equivalent of System.out::println?

What is the Lambda Expression Equivalent of System.out::println?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 15:16:30769browse

What is the Lambda Expression Equivalent of System.out::println?

Exploring the Lambda Expression Equivalent of System.out::println

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:

  1. Storing the evaluated System.out object in a variable:

    <code class="java">PrintStream p = Objects.requireNonNull(System.out);</code>
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn