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:
<
In Java 8 Comparator<T>
is annotated with @FunctionalInterface
. It's documentation says:
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
If a type is annotated with this annotation type, compilers are required to generate an error message unless:
The type is an interface type and not an annotation type, enum, or class. The annotated type satisfies the requirements of a functional interface. However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.
The most important part here is that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.
, which answers your question.
A comparator is basically just a function which takes two parameters and returns an int.
Effectively what's happening here is that the compiler is able to cleverly infer what the right-hand side needs to be because of how you declared the left-hand side.
Comparator<Duck> byWeight = (d1,d2) -> d1.getWeight() - d2.getWeight();
//^ ^ I know a Comparator<Duck> takes two Ducks.
// ^ I know a Comparator<Duck> returns an int
This is all possible because a Comparator<T> is defined as a functional interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
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<Duck> byWeight = (d1,d2) -> { d1.getWeight() - d2.getWeight(); }