I have a class Care
class Car{
private int wheels;
private int doors;
...
public int getWheels(){ return wheels;}
public int getDoors(){ return doors:}
}
And I have a collection of the cars
List<Car> cars = ...
I want to calculate the average numbers of doors and windows in the collection. I could do this:
cars.stream().mapToInt(Car::getWheels).avg().orElse(0.0)
cars.stream().mapToInt(Car::getDoors).avg().orElse(0.0)
However, I want to create a dynamic function for this, for example:
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;
}
However, .mapToInt()
requires ToIntFunction<? super T> mapper
as argument, but the method reference is Function<Car,Integer>
, and casting does not work.
However when I directly pass the method reference, for example .mapToInt(Car::getDoors)
, it works.
How to cast correctly cast Function<Car,Integer>
to required type then?
question from:
https://stackoverflow.com/questions/65847854/return-method-refference-to-stream 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…