Home >Java >javaTutorial >When is a Method Reference Not Equivalent to a Lambda Expression?

When is a Method Reference Not Equivalent to a Lambda Expression?

DDD
DDDOriginal
2024-11-04 00:29:30298browse

When is a Method Reference Not Equivalent to a Lambda Expression?

Method Reference vs Lambda Expression: Exploring the Equivalency of System.out::println

When utilizing a method reference such as System.out::println, the function first evaluates System.out and captures the resulting value in a lambda expression. For instance, the lambda equivalent of this method reference would be:

<code class="java">Consumer<Integer> consumer = System.out::println;</code>

This lambda expression behaves similarly to the code below:

<code class="java">Consumer<Integer> consumer = new Consumer<Integer>() {
    @Override
    public void accept(Integer i) {
        System.out.println(i);
    }
};</code>

However, the method reference System.out::println offers an advantage over the lambda expression as it always evaluates System.out at compile time. In the case of the lambda expression, System.out is evaluated each time the method is invoked.

To ensure an exact equivalent to the method reference, the following code must be used:

<code class="java">PrintStream printStream = Objects.requireNonNull(System.out);
Consumer<Integer> consumer = o -> printStream.println(o);</code>

Here, printStream is a variable capturing the System.out value, guaranteeing that any subsequent changes to System.out will not affect this consumer.

The above is the detailed content of When is a Method Reference Not Equivalent to a Lambda Expression?. 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