且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-23 09:15:28

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

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.