Java 8 stream max() function argument type Comparator vs Comparable

前端 未结 4 1835
陌清茗
陌清茗 2021-01-01 16:41

I wrote some simple code like below. This class works fine without any errors.

public class Test {
    public static void main(String[] args) {
        List&         


        
4条回答
  •  自闭症患者
    2021-01-01 16:54

    Integer implements Comparable by overriding compareTo.

    That overriden compareTo, however, can be used in a way that satisfies and implements the Comparator interface.

    In its usage here

    int value = intList.stream().max(Integer::compareTo).get();
    

    it's translated to something like

    int value = intList.stream().max(new Comparator() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1.compareTo(o2);
        }
    }).get();
    

    A method reference (or lambda expression) must satisfy the signature of the corresponding functional interface's single abstract method and, in this case (Comparator), compareTo does.


    The idea is that max expects a Comparator and its compare method expects two Integer objects. Integer::compareTo can satisfy those expectations because it also expects two Integer objects. The first is its receiver (the instance on which the method is to be called) and the second is the argument. With the new Java 8 syntax, the compiler translates one style to the other.

    (compareTo also returns an int as required by Comparator#compare.)

提交回复
热议问题