gpt4 book ai didi

java - lambda 表达式和实例化方法引用之间的不同行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:37 26 4
gpt4 key购买 nike

据我所知,lambda 表达式可以毫无问题地替换为方法引用。我的 IDE 说的是一样的,但下面的例子显示了相反的情况。方法引用显然返回相同的对象,而 lambda 表达式每次都返回新对象。

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Instance {

int member;

Instance set(int value){
this.member = value;
return this;
}

@Override
public String toString() {
return member + "";
}

public static void main(String[] args) {

Stream<Integer> stream1 = Stream.of(1, 2, 3, 4);
Stream<Integer> stream2 = Stream.of(1, 2, 3, 4);

List<Instance> collect1 = stream1.map(i -> new Instance().set(i)).collect(Collectors.toList());
List<Instance> collect2 = stream2.map(new Instance()::set).collect(Collectors.toList());

System.out.println(collect1);
System.out.println(collect2);
}
}

这是我的输出:

[1, 2, 3, 4]
[4, 4, 4, 4]

最佳答案

方法引用表达式评估的时间不同于哪个 lambda 表达式。
对于在 :: 之前有表达式(而不是类型)的方法引用,子表达式会立即被求值,求值结果会被存储并随后重用。
所以在这里:

new Instance()::set

new Instance() 计算一次。

来自 15.12.4. Run-Time Evaluation of Method Invocation (重点是我的):

The timing of method reference expression evaluation is more complex than that of lambda expressions (§15.27.4). When a method reference expression has an expression (rather than a type) preceding the :: separator, that subexpression is evaluated immediately. The result of evaluation is stored until the method of the corresponding functional interface type is invoked; at that point, the result is used as the target reference for the invocation. This means the expression preceding the :: separator is evaluated only when the program encounters the method reference expression, and is not re-evaluated on subsequent invocations on the functional interface type.

关于java - lambda 表达式和实例化方法引用之间的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52097251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com