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

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

Linda Hamilton
Release: 2024-11-03 15:16:30
Original
799 people have browsed it

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>
Copy after login

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>
    Copy after login
  2. Using the stored variable in the lambda expression:

    <code class="java">numbers.forEach(o -> p.println(o));</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template