Why can a lambda expression be used as a Comparator?

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

    Lambda expression is just a short-hand for a functional interface (an interface with just one function), you don't need to write new/function name just write parameter list in ( yourParameterListHere ) and then -> and after this write what to do/return (i.e function body). you can also write it with { } like

    Comparator byWeight = (d1,d2) -> { d1.getWeight() - d2.getWeight(); }
    

提交回复
热议问题