Java中stream.max(Comparator)和stream.collect(Collectors.maxBy(Comparator)的区别 [英] Difference between stream.max(Comparator) and stream.collect(Collectors.maxBy(Comparator) in Java

查看:43
本文介绍了Java中stream.max(Comparator)和stream.collect(Collectors.maxBy(Comparator)的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java Streams 中 - stream.max(Comparator)stream.collect(Collectors.maxBy(Comparator)) 在性能方面有什么区别.两者都将根据传递的比较器获取最大值.如果是这种情况,为什么我们需要使用 collect 方法进行收集的额外步骤?我们什么时候应该选择前者和后者?哪些用例场景适合同时使用两者?

In Java Streams - what is the difference between stream.max(Comparator) and stream.collect(Collectors.maxBy(Comparator)) in terms of preformance. Both will fetch the max based on the comparator being passed. If this is the case why do we need the additional step of collecting using the collect method? When should we choose former vs latter? What are the use case scenarios suited for using both?

推荐答案

他们做同样的事情,共享同样的代码.

They do the same thing, and share the same code.

为什么我们需要使用 collect 方法进行收集的额外步骤?

why do we need the additional step of collecting using the collect method?

你没有.如果您想要这样做,请使用 max().但在某些情况下,收集器可以派上用场.例如:

You don't. Use max() if that's what you want to do. But there are cases where a Collector can be handy. For example:

Optional<Foo> result = stream.collect(createCollector());

其中 createCollector() 将根据某些条件返回一个收集器,可能是 maxBy、minBy 或其他条件.

where createCollector() would return a collector based on some condition, which could be maxBy, minBy, or something else.

一般来说,您不应该太在意执行相同操作的两种方法之间可能存在的微小性能差异,并且很有可能以相同的方式实现.相反,您应该使您的代码尽可能清晰易读.

In general, you shouldn't care too much about the small performance differences that might exist between two methods that do the same thing, and have a huge chance of being implemented the same way. Instead, you should make your code as clear and readable as possible.

这篇关于Java中stream.max(Comparator)和stream.collect(Collectors.maxBy(Comparator)的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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