public class Car {
private int maxSpeed;
public Car(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
public int getMaxSpeed() {
return maxSpeed;
}
}
我们可以按以下方式对汽车列表进行排序:
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));
如果我们看到方法的签名Comparator.comparing
,输入参数类型为Function<? super T, ? extends U>
在上面的例子中,如何Car::getMaxSpeed
被投射到Function<? super T, ? extends U>
而以下内容无法编译?
Function<Void, Integer> function = Car::getMaxSpeed;
那是因为getMaxSpeed
方法是一个Function<Car, Integer>
.
Namely:
<Car, Integer> Comparator<Car> java.util.Comparator.comparing(
Function<? super Car, ? extends Integer> keyExtractor
)
Note
为了参考getMaxSpeed
从一个实例Car
与::
习语,你必须声明一个Car
带签名的方法:getMaxSpeed(Car car)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)