I have seen that in Java 8, one can define a comparator like this:
Comparator c = (Computer c1, Computer c2) -> c1.getAge().compareTo(c2.getAge());
which is equivalent to:
Comparator d = new Comparator<Computer> () {
@Override
public int compare(Computer c1, Computer c2){
return c1.getAge().compareTo(c2.getAge());
}
};
I'd like to understand how this works. In the second example, it is fairly simple: A Comparator
object is created with a method compare
which performs the comparison by using the compareTo
method in the age
property of Computer
. This method is simply called by us when we do:
Computer comp1 = new Computer(10);
Computer comp2 = new Computer(11);
d.compare(comp1, comp2); // -1
But what's going on in the first example, when using a lambda? It looks to me like we are setting the Comparator
to be equal to a method that performs comparison. But this cannot be, because a Comparator
object is an object that has a method compare
. I've learned that lambdas can be used with functional interfaces (interfaces with only one method). But Comparator
is not a functional interface (it has many other methods other than compare
!). So how does the Java interpreter know that it is the compare
method we are implementing?