Search code examples
javacomparatormethod-reference

Does Java Integer class have a compare method which returns Comparator?


I was reading the Java tutorial and saw this line of code:

Comparator<Integer> normal = Integer::compare;

About the right hand side, I tried looking for documentation which explains how compare returns a Comparator for an Integer object. But I found none. The Java API docs show the following:

public static int compare(int x, int y)

What am I missing?


Solution

  • Comparator<T> is a functional interface with the signature int compare(T o1, T o2);. From the documentation of java.util.function: "Functional interfaces provide target types for lambda expressions and method references."

    The method Integer#compare(int x, int y) matches this signature. Its method reference can therefore be assigned to a variable of type Comparator<Integer>.

    To better understand this, I suggest that you read about lambda expressions, method references and functional interfaces.