Why can a lambda expression be used as a Comparator?

comparator functional interface
java priority queue comparator
priority queue comparator lambda java
comparator anonymous class
collections binarysearch lambda
comparable and comparator using lambda
lambda expression java example mkyong
inline comparator java

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:

Comparator<Duck> byWeight = new Comparator<Duck>(){
    public int compare(Duck d1, Duck d2){
        return d1.getWeight() - d2.getWeight();
    }
};

This I can understand. According to the book this can be replaced with a lambda expression like this:

Comparator<Duck> byWeight = (d1,d2) -> d1.getWeight() - d2.getWeight();

Now this I don't understand. The lambda expression does not return a Comparator object, which it couldn't now that I think of it since Comparator is an interface.

So does the new operator in the first example refer to the anonymous class that is being made which is called Comparator because that anonymous class implements the Comparator interface?

What exactly is happening in example 2 then? Is an object created somehow out of the lambda expression? In this example you use byWeight as a reference variable right?

I really don't understand this, could anyone please explain? Thank you.


If you read the documentation of the Comparator interface, you can read:

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

The Comparator<T> interface is thus implemented like:

@FunctionalInterface
public interface Comparator<T> {

    int compare(T o1, T o2);

    // ...

}

Now if we look at the documentation of @FunctionalInterface we see:

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.

So basically if you have an interface with one abstract method, and you annotate the interface as a @FunctionalInterface, then that interface is a target for functions: in that you more or less construct an anonymous class that implements the functional interface and the function you specify is the implementation of the only abstract method.

In other words, the expression:

Comparator<Duck> byWeight = <somelambda>

is equivalent to:

Comparator<Duck> byWeight = new Comparator<Duck>(){
    public int compare(Duck d1, Duck d2){
        return <somelambda>(d1,d2);
    }
}

Comparator interface in java is a functional interface why? (Java in , In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List. 1. Classic Comparator example. With Java8 Comparator is a @FunctionalInterface which makes it usable with lambda expressions. That is you can define a Bi-Function (function with two arguments) with return type int and use it as Comparator, which is done in your second example. Both Comparator instances can be used in exactly the same way in your remaining code.


In the first code block the created object instance implements Comparator<Duck>, but the corresponding class has no name (is anonymous).

In the second code block, the same thing happens. Because the Comparator interface only defines a single method (named compare), it is possible to abbreviate the creation of an (anonymous) implementation of the interface using a lambda expression.

The variable byWeight can be used the same way in both examples. Everywhere a Comparator<Duck> is required, byWeight can be used - which corresponds to the type information of the variable. Internally, whenever compare is invoked on this implementation, the definition provided using the lambda expression is used.

Is Comparable Interface a FunctionalInterface?, Though, some of you might have a doubt that, can we use lambda expression with Comparator? because it's an old interface and may not implement functional​  Here Lambda expression can be used to implement comparator because Comparator is a Functional Interface. Lambda expression provides implementation of the functional interface. See some of the Lambda expression examples here – http://netjs.blogspot.in/2015/06/lambda-expression-examples-in-java-8.html


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.

Java 8 Lambda Comparator example for Sorting List of Custom , Comparator is used when we want to sort a collection of objects which can be This comparison can be done using Comparable interface as well, but it restrict based on non-string class members like id or age, using Lambda expressions? Java 8 Comparator example with lambda. Comparator is used when we want to sort a collection of objects which can be compared with each other. This comparison can be done using Comparable interface as well, but it restrict you compare these objects in a single particular way only.


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.

Java 8 Lambda : Comparator example, Elegant Sort in Java 8 - Lambda Expressions go right past syntactic Now let's see how we can use a custom Comparator with the sorted() API  A lambda expression used with any functional interface and Comparator is a functional interface. The Comparator interface has used when sorting a collection of objects compared with each other. In the below example, we can sort the employee list by name using the Comparator interface.


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

Java 8 Comparator Example Using Lambda Expressions, A lambda expression is an anonymous method and doesn't execute on its own in java. Instead, it is used to implement a method defined by the  Lambda expressions enable you to represent a method interface with an expression. They’re great for getting rid of anonymous inner classes, which is exactly what you’re going to see here. Here’s an example of a lambda expression that instantiates a Comparator object: 1


Java 8 Comparator example with lambda, A lambda expression is a block of code that can be passed around to execute. It is a The following example shows how to use a comparator to sort an array of  (Dog m, Dog n) -> Integer.compare(m.getWeight(), n.getWeight()) is a lambda expression. It is converted to an object of Comparator behind the scene. For now let's simply consider the lambda expression as a function. How lambda expressions are converted to objects of functional interfaces is a more complicated story. 3. Syntax of Lambda Expression


Java 8, The idea behind this is that you can use lambdas wherever you'd otherwise use functional interfaces to pass along functions. If you remember our Comparator  Using lambda expression, sequential and parallel execution can be achieved by passing behavior into methods. In the Java world, lambdas can be thought of as an anonymous method with a more compact syntax. Here compact means that it is not mandatory to specify access modifiers, return type and parameter types while defining the expression.


How to write the comparator as a lambda expression in Java?, We can use Comparator interface to sort, It only contain one abstract method: – compare(). An interface that only contain only a single abstract method then it is  As you can see here, we have used lambda expression for using Comparator. So in spite of writing Anonymous comparator, our expression became very easy. So in spite of writing Anonymous comparator, our expression became very easy.