Why can a lambda expression be used as a Comparator?

后端 未结 9 1936
渐次进展
渐次进展 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:09

    The interface Comparator is a Functional Interface, this means this interface can only contains one abstract method.

    Then you can use lambda expression to define the implementation of this abstract method, basically (d1,d2) -> d1.getWeight() - d2.getWeight(); is the implementation of the abstract method int compare(T o1, T o2);.

    As a functionnal Interface contains only one abstract method, you can use lambda expression to define the implementation of such interface

提交回复
热议问题