为什么Double :: compareTo可以用作Stream.max(Comparator<?super T>比较器)的参数 [英] Why Double::compareTo can be used as an argument of Stream.max(Comparator<? super T> comparator)

查看:438
本文介绍了为什么Double :: compareTo可以用作Stream.max(Comparator<?super T>比较器)的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stream.max的api需要一个Comparator<? super T>类型的参数,而Comparator的唯一抽象方法是

The api for Stream.max requires an argument of type Comparator<? super T>, and for Comparator, the only abstract method is

int compare(T o1, T o2)

但是Double::compareTocompareTo api是

public int compareTo(Double anotherDouble)

为什么只提供一个参数,为什么Double::compareTo可以用作Stream的参数

why just provide one argument, so why can Double::compareTo use as argument of Stream

Optional<T> max(Comparator<? super T> comparator)

推荐答案

以下MyComparator实现了Comparator.它有两个参数.
与lambda表达式(d1,d2) -> d1.compareTo(d2)
相同 并与方法参考Double::compareTo

The below MyComparator implement a Comparator. It takes two arguments.
It's the same as the lambda expression (d1,d2) -> d1.compareTo(d2)
and the same as the method reference Double::compareTo

方法引用是相同的,因为d1Double,因此Java假定要在第一个Double上调用compareTo方法.另一个参数d2成为所调用方法的参数. @Andronicus也很好地解释了这一点.

The method reference is the same because d1 is a Double, so Java assumes the compareTo method is to be called on the first Double. The other argument d2 becomes the argument for the method called. This is also very nicely explained by @Andronicus.

此示例中的3个变体是等效的:

The 3 variants in this example are equivalent:

import java.util.List;
import java.util.Comparator;

class MyComparator implements Comparator<Double> {
  public int compare(Double d1, Double d2) {    // (d1,d2) ->
    return d1.compareTo(d2);                    // d1.compareTo(d2)
  }
}

public class Testing {
    public static void main(String[] args) {
      List<Double> list = List.of(1.1,2.2,3.3,4.4,5.5,6.6,7.7);

      Double maxClass =
        list.stream()
            .max(new MyComparator())
            .orElse(Double.NEGATIVE_INFINITY);

      Double maxLamdba =
        list.stream()
            .max((d1,d2) -> d1.compareTo(d2))
            .orElse(Double.NEGATIVE_INFINITY);

      Double maxMethodreference =
        list.stream()
            .max(Double::compareTo)
            .orElse(Double.NEGATIVE_INFINITY);
   }
}

这篇关于为什么Double :: compareTo可以用作Stream.max(Comparator&lt;?super T&gt;比较器)的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆