java的max函数,Java 8流max()函数参数类型Comparator与Comparable

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

public class Test {

public static void main(String[] args) {

List intList = IntStream.of(1,2,3,4,5,6,7,8,9,10).boxed().collect(Collectors.toList());

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

//int value = intList.stream().max( comparator type should pass here>).get();

System.out.println("value :"+value);

}

}

As the code comment shows the max() method should pass an argument of type Comparator super Integer>.

But Integer::compareTo implements Comparable interface - not Comparator.

public final class Integer extends Number implements Comparable {

public int compareTo(Integer anotherInteger) {

return compare(this.value, anotherInteger.value);

}

}

How can this work? The max() method says it needs a Comparator argument, but it works with Comparable argument.

I know I have misunderstood something, but I do now know what. Can someone please explain?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值