saravana_pc saravana_pc - 1 year ago 121
Java Question

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<>();


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

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

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

Answer Source

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


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


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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download