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:
Listnumbers = 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!