Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

java - return method refference to stream

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should not cast a Function to a ToIntFunction as they are not associated (ToIntFunction does not extend Function). They are however both functional interfaces, so the method reference can also be inferred directly as a ToIntFunction.

There is an average() method defined in IntStream:

public double calculateAvgOfProperty(List<Car> cars, String property) {
    ToIntFunction<Car> mapper = decideMapper(property);
    return cars.stream().mapToInt(mapper).average().orElse(0.0);
}

public ToIntFunction<Car> decideMapper(String ppr){
     if( ppr.equals("doors"))  return Car::getDoors;
     if( ppr.equals("wheels")) return Car::getWheels;
     ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...