Java 中 stream.max(Comparator) 和 stream.collect(Collectors.maxBy(Comparator) 的区别区别、max、stream、Java

2023-09-07 01:24:45 作者:青春如手纸丶没事就少扯

在 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());

where 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.