一、lambda
List<Apple> inventory = new ArrayList<>();
inventory.addAll(Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")));
1、匿名内部类
inventory.sort(new Comparator<Apple>() {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}});
2、lambda与函数式接口
inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
Java 8增加了一种特殊的注解@FunctionalInterface,表明接口为函数式接口,接口默认方法不影响函数式接口契约
3、方法引用
inventory.sort(comparing(Apple::getWeight));
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
网友评论