Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an instance of Comparable to a method that expects a Comparator

The Stream class in Java 8 defines a max method that requires a Comparator argument. Here is the method signature:

Optional<T> max(Comparator<? super T> comparator)

Comparator is a functional interface that has an abstract compare method with this signature. Notice compare requires 2 arguments.

int compare(T o1, T o2)

The Comparable interface has an abstract compareTo method with this signature. Notice compareTo requires only 1 argument.

int compareTo(T o)

In Java 8, the following code works perfectly. However, I expected a compilation error like, "the Integer class does not define compareTo(Integer, Integer)".

int max = Stream.of(0, 4, 1, 5).max(Integer::compareTo).get();

Can someone help explain why it's possible to pass an instance of Comparable to a method that expects an instance of Comparator even though their method signatures are not compatible?

like image 272
Bryan Avatar asked May 17 '14 14:05

Bryan


1 Answers

That's a nice feature about method references. Note that Integer::compareTo is an instance method. You need two Integer objects to call it. One on the left side (the target object), and one on the right side (the first and only parameter).

So Integer::compareTo is a method reference for a method, that expects two Integer objects and returns an int. Comparator<Integer> is a functional interface for functions, that expect two Integer objects and return an int. That's the reason why it works.

like image 99
nosid Avatar answered Sep 21 '22 16:09

nosid