Home >Java >javaTutorial >What is the lambda expression equivalent to the System.out::println method reference?

What is the lambda expression equivalent to the System.out::println method reference?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 06:26:02897browse

What is the lambda expression equivalent to the System.out::println method reference?

Equivalence of System.out::println Method Reference in Lambda Expression

In Java, the method reference System.out::println allows for a concise way to refer to the System.out.println() method. It evaluates System.out and assigns it to a variable.

Question:

What is the corresponding lambda expression for System.out::println that provides the same behavior?

Answer:

An exact equivalent lambda expression would be:

num -> {
    PrintStream p = Objects.requireNonNull(System.out);
    p.println(num);
}

This lambda expression captures the reference to System.out in the variable p before executing the println method. This prevents any changes to System.out from affecting the behavior of the lambda expression.

Difference from Simple Lambda Expression:

A simpler lambda expression like num -> System.out.println(num) would evaluate System.out each time it's called, making it susceptible to changes in System.out while the lambda is executed.

Usage:

The equivalent lambda expression can be used in the same way as System.out::println, such as:

List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
numbers.forEach(num -> {
    PrintStream p = Objects.requireNonNull(System.out);
    p.println(num);
});

This code will print the numbers in the list to the console.

The above is the detailed content of What is the lambda expression equivalent to the System.out::println method reference?. 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