何时使用专门的流方法而不是Collectors类中的方法,反之亦然? [英] When to use specialised stream methods over methods in the Collectors class or vice versa?
问题描述
我们可以看到收藏家 class包含许多常见聚合操作的工厂方法。列举一些 summingXXX
, averagingXXX
, maxBy
, minBy
。
We can see that the Collectors class contains factory methods for many common aggregation operations. to name a few summingXXX
, averagingXXX
, maxBy
, minBy
.
这些方法实际上是与专用流上的调用方法相比的重复功能。以 IntStream 为例有一个 sum()
, average()
, max()
和 min()
。
These methods are actually duplicate functionality over calling methods on specialised streams. take for example IntStream, this has a sum()
, average()
, max()
and min()
respectively.
时不时我看到人们可以互换地使用属于Collectors类和专用流方法的方法。
Every now and then I see people using the methods which belong to the Collectors class and specialized stream methods interchangeably.
例如,假设我们有一个 List< Employee>
并且想要获得平均工资,你可以使用专业原始流中的方法。
For example, assuming we have a List<Employee>
and one wants to get the average salary, you can either use the methods in the specialised primitive streams.
OptionalDouble averageUsingIntStream =
employees.stream()
.mapToInt(Employee::getSalary)
.average();
或使用收藏家
中的工厂方法class。
or use the factory methods in the Collectors
class.
Double averageUsingCollectors =
employees.stream()
.collect(Collectors.averagingInt(Employee::getSalary));
现在,我的问题是这个重复功能的动机是什么,在哪种情况下它更好使用第一种方法还是第二种方法?
Now, my question is what is the motivation behind this duplicate functionality and in which situation is it better to use the first approach or the second?
推荐答案
收集器类中所述工厂方法存在的真正动机将用作下游收集器,即Java运行时应用于另一个收集器的结果的收集器。这使得人们可以组合在一起并执行更复杂的聚合。
The real motivation for the said factory methods in the Collectors class to exist is to be used as downstream collectors i.e. a collector that the Java runtime applies to the results of another collector. This enables one to compose together and perform more complex aggregations.
例如,有 groupingBy 接受下游收集器的收集器 collectAndThen , partitioningBy , flatMapping (java-9)等。
For example, there are groupingBy collectors that accept a downstream collector, collectingAndThen, partitioningBy, flatMapping (java-9) et al.
因此,经验法则是只将问题中的上述方法用作下游收集器。
So the rule of thumb is to only use the aforementioned methods in the question as downstream collectors.
专用原始流也更有效,所以如果你想做的就是计算 sum()
, average()
, max()
或 min()
然后我会坚持原始专业化。
The specialised primitive streams are also more efficient so if all you want to do is compute the sum()
, average()
, max()
or min()
then I'd stick with the primitive specialisation.
这篇关于何时使用专门的流方法而不是Collectors类中的方法,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!