13

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?

3
  • Related: stackoverflow.com/questions/22561614/… (you could use Integer::compare instead of Integer::compareTo)
    – Marco13
    May 17, 2014 at 14:26
  • You're not passing an Integer instance. You're passing a reference to the method Integer.compareTo(). That's quite different.
    – JB Nizet
    May 17, 2014 at 16:16
  • This works perfectly. However, using Comparator.naturalOrder() for types implementing Comparable is potentially more efficient.
    – Holger
    May 18, 2014 at 9:24

1 Answer 1

13

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.

2
  • BTW, Comparator<? super Integer> compareTo = Integer::compareTo; also compiles perfectly. May 17, 2014 at 14:41
  • 2
    I see, so Integer::compareTo is equivalent to (a, b) > a.compareTo(b)?
    – Bryan
    May 17, 2014 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.