java8之一——lambda表达式

一、lambda

List inventory = new ArrayList<>();
inventory.addAll(Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")));

1、匿名内部类

inventory.sort(new Comparator() {
            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 {
int compare(T o1, T o2);
boolean equals(Object obj);
}

Java 8增加了一种特殊的注解@FunctionalInterface,表明接口为函数式接口,接口默认方法不影响函数式接口契约

3、方法引用

inventory.sort(comparing(Apple::getWeight));

public static > Comparator comparing(
            Function keyExtractor)
    {
        Objects.requireNonNull(keyExtractor);
        return (Comparator & Serializable)
            (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
    }

你可能感兴趣的:(java8之一——lambda表达式)