java – Java 8 stream’s .min () and .max (): why is it compiled?

Let me tell you what’s going on here, because it’s not obvious!

First of all, Stream.max() accepts an instance of Comparator so that the elements in the stream can be compared to each other to find the minimum or maximum, in an optimal order that you don’t need to worry too much about.

So the question is, of course, why it is Integer::max accepted? It is not a comparator after all!

The answer is in how the new lambda functionality works in Java 8. It is based on a concept that is informally known as “single abstract method” interfaces or “SAM” interfaces. The idea is that any interface with an abstract method can be automatically implemented by any lambda – or method reference – whose method signature is a match for the only method on the interface. Then looking into the interface Comparator (simple version):

public Comparator {
    T compare(T o1, T o2);

If a method is looking for a Comparatorthen it is essentially looking for this signature:

int xxx(Integer o1, Integer o2);

I use “xxx” because the method name is not used for matching purposes .

Therefore, be it Integer.min(int a, int b) that Integer.max(int a, int b) they are close enough to allow this code to be automatically displayed as Comparator in a context of method.

Leave a comment