【发布时间】:2021-01-22 15:18:51
【问题描述】:
我有一堂课Care
class Car{
private int wheels;
private int doors;
...
public int getWheels(){ return wheels;}
public int getDoors(){ return doors:}
}
我收藏了一些汽车
List<Car> cars = ...
我想计算集合中门窗的平均数量。我可以这样做:
cars.stream().mapToInt(Car::getWheels).avg().orElse(0.0)
cars.stream().mapToInt(Car::getDoors).avg().orElse(0.0)
但是,我想为此创建一个动态函数,例如:
public double calculateAvgOfProperty(List<Car> cars, String property){
Function<Car,Integer> mapper = decideMapper(property);
return cars.stream().maptoInt(mapper).avg().orElse(0.0);
}
public Function<Car,Integer> decideMapper(String ppr){
if( ppr.equals("doors") return Car::getDoors;
if( ppr.equals("wheels") return Car::getWheels;
}
但是,.mapToInt() 需要ToIntFunction<? super T> mapper 作为参数,但方法引用是Function<Car,Integer>,并且强制转换不起作用。
但是,当我直接传递方法引用时,例如.mapToInt(Car::getDoors),它可以工作。
那么如何正确地将Function<Car,Integer> 转换为所需的类型?
【问题讨论】:
-
只是猜测:您不能将方法签名中的返回类型更改为
? extends Car(或类似的东西)吗? -
请注意:我不确定
.avg()在IntStream实例上是否可用。
标签: java java-stream method-reference