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

前端 未结 4 1838
陌清茗
陌清茗 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 17:02

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

    The above snippet of code is logically equivalent to the following:

    int value = intList.stream().max((a, b) -> a.compareTo(b)).get();
    

    Which is also logically equivalent to the following:

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

    Comparator is a functional interface and can be used as a lambda or method reference, which is why your code compiles and executes successfully.

    I recommend reading Oracle's tutorial on Method References (they use an example where two objects are compared) as well as the Java Language Specification on §15.13. Method Reference Expressions to understand why this works.

提交回复
热议问题