假设您有以下代码:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
public static void main(String[] s) {
Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
}
static boolean f(String s) {
System.out.println("creating a value for \""+s+'"');
return s.isEmpty();
}
}
然后,您将看到消息creating a value for "snoop"
恰好一次,就像在第二次调用时computeIfAbsent
已经存在该键的值一样。的k
在λ表达式k -> f(k)
仅仅是该地图将传递到您的拉姆达用于计算值的键一个placeolder(参数)。因此,在示例中,键被传递给函数调用。
或者,您可以编写:whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty());
在没有辅助方法的情况下获得相同的结果(但是您将看不到调试输出)。甚至更简单,因为它是对现有方法的简单委托,因此您可以编写:whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty);
此委托不需要编写任何参数。
为了更接近问题中的示例,您可以将其写为whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key));
(命名参数k
还是都没有关系key
)。或将其编写为whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut);
好像tryToLetOut
是static
或whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut);
如果tryToLetOut
是实例方法。