Method reference in Java 8

public class Car {

    private int maxSpeed;

    public Car(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }
}

We can sort a list of cars by,

    Car carX = new Car(155);
    Car carY = new Car(140);

    List<Car> cars = new ArrayList<>();
    cars.add(carX);
    cars.add(carY);

    cars.sort(Comparator.comparing(Car::getMaxSpeed));

If we see the signature of the method Comparator.comparing, the input parameter type is Function<? super T, ? extends U>

In the above example, how is Car::getMaxSpeed being cast to Function<? super T, ? extends U> while the following does not compile?

  Function<Void, Integer> function = Car::getMaxSpeed;

Answer

That is because the getMaxSpeed method is a Function<Car, Integer>.

Namely:

<Car, Integer> Comparator<Car> java.util.Comparator.comparing(
    Function<? super Car, ? extends Integer> keyExtractor
)

Note

In order to reference getMaxSpeed from an instance of Car with the :: idiom, you would have to declare a Car method with signature: getMaxSpeed(Car car).

Attribution
Source : Link , Question Author : saravana_pc , Answer Author : Mena

Leave a Comment