Java8方法引用

Java8方法引用,java,Java,作为任意方法引用的一部分: 为什么这是允许的 Predicate<String> p1 = String::isEmpty; 谓词p1=String::isEmpty; 为什么这是不允许的 BiConsumer<HashMap<String,Integer>, Integer> b1 = HashMap<String,Integer>::put; biconsumerb1=HashMap::put; 在第一个示例中,您正在创建一个谓词,它将一

作为任意方法引用的一部分:

为什么这是允许的

Predicate<String> p1 = String::isEmpty;
谓词p1=String::isEmpty;
为什么这是不允许的

BiConsumer<HashMap<String,Integer>, Integer> b1 = HashMap<String,Integer>::put;
biconsumerb1=HashMap::put;

在第一个示例中,您正在创建一个
谓词
,它将一个
字符串
作为输入。这与不接受任何参数的
String.isEmpty()
匹配。谓词仅对字符串实例进行操作

对于第二个示例,让我们检查
put
方法:

public V put(K键,V值)
由于您使用的是
HashMap
,因此

public Integer put(String key, Integer value)
如您所见,该方法本身需要两个参数。由于要将其作为方法引用传递,因此除了两个参数外,还需要
HashMap

BiConsumer<HashMap<String, Integer>, Integer> b1 = HashMap<String, Integer>::put;
不需要
@functioninterface
注释,但它向读者传达了这样一个意图,即该接口可以用作lambda表达式或方法引用的赋值目标

现在,您可以将引用分配给
put

TriConsumer<HashMap<String, Integer>, String, Integer> consumer = HashMap<String, Integer>::put;

HashMap<String, Integer> map = new HashMap<>();
consumer.accept(map, "Key", 123);
System.out.println(map.get("Key")); // prints 123
TriConsumer consumer=HashMap::put;
HashMap=newHashMap();
消费者接受(地图,“钥匙”,123);
System.out.println(map.get(“Key”);//印刷品123

基本问题是,
put()
不是类型化方法-类型具有方法作用域且可以推断的方法,它是泛型实例方法-从实例类型获取其类型的方法

此外,您还与方法引用的类型及其泛型参数不匹配。我想你指的是双功能,而不是双消费者

让我们看看什么是有效的:


正如我所说的,因为该方法从实例获取其类型,所以您需要一个类型化实例。

您的意思是现在还是不?理解,因为在上述情况下,无法推断put的参数。这将在BiConsumer b1=HashSet::add;谢谢你解释得这么好@VijayNarayanan我很高兴能帮上忙!一定要看看波希米亚的答案,他的例子展示了如何为特定对象的方法指定引用。非常感谢您的解释!
TriConsumer<HashMap<String, Integer>, String, Integer> consumer = HashMap<String, Integer>::put;

HashMap<String, Integer> map = new HashMap<>();
consumer.accept(map, "Key", 123);
System.out.println(map.get("Key")); // prints 123
HashMap<String, Integer> instance = new HashMap<>();
BiFunction<String, Integer, Integer> b1 = instance::put;
BiConsumer<String, Integer> b1 = instance::put;