有人可以建议,为什么我不能在这里申请方法参考?
工作代码。
System.out.println(
Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting())));
编译错误,无法解决方法
System.out.println(
Arrays.stream(str.split(" "))
.collect(Collectors.groupingBy(Function::identity,Collectors::counting)));
因为groupingBy()
期望Function
,即采用单个参数并返回某些内容的内容。
Function.identity()
返回一个函数。
但是Function::identity
references identity()
方法,该方法不接受任何参数,因此不能用作函数。
类似地,groupingBy()
期望将Collector
的实例作为第二个参数。 Collectors.counting()
返回一个收集器。因此您可以使用它。但是Collector::counting
引用了counting()
方法,没有参数的单个方法根本不足以提供具有5个方法的Collector接口的实现。]
要进行汽车类比,如果调用的方法是期望汽车的汽车,则可以调用garage.getCar()
以获取汽车,并将返回的汽车作为参数传递。但是通过garage::getCar
是没有意义的,因为那将是“能够为您提供汽车的东西”。那不算是车辆。