Why can a lambda expression be used as a Comparator?

后端 未结 9 1935
渐次进展
渐次进展 2020-12-16 02:55

In the book OCP Study Guide there is this example about a Comparator that can be initialized in two ways. The first is via an anonymous class like this:

<         


        
9条回答
  •  北海茫月
    2020-12-16 03:11

    You can think of a lambda as a method that doesn't belong to a class, that can be passed around like a piece of data.

    Or, with a very small mental shift, you can think of it as an object with only one method.

    There is a set of interfaces marked as functional interfaces. This is mentioned in the Javadoc as:

    Functional Interface:

    This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

    That's a technical way of saying that because they have only one method, and they're marked as functional, the compiler can treat a lambda as an object with that interface. It knows to use the lambda as the implementation of the one method in the interface.

    So you can do:

    Comparator byNameComparator = (f1,f2) -> f1.name().compareTo(f2.name());
    Predicate isVip = cust -> cust.orderCount > 20;
    Callable getResult = () -> queue.getItem();
    Function multiply = (a,b) -> a * b;
    

    ... and so on.

    And wherever a parameter's type is a functional interface, you can instead use a lambda directly, so given:

     public void sort(Comparator cmp);
    

    ... you can call it as:

     foo.sort( (a,b) -> a.name().compareTo(b.name()));
    

提交回复
热议问题