计数流的元素 [英] Counting elements of a Stream

查看:125
本文介绍了计数流的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算一个流的不同元素,我想知道为什么

I want to count the different elements of a stream and am wondering why

Stream<String> stream = Stream.of("a", "b", "a", "c", "c", "a", "a", "d");
Map<String, Integer> counter1 = stream.collect(Collectors.toMap(s -> s, 1, Integer::sum));

无法使用。 Eclipse告诉我

doesn't work. Eclipse tells me


类型Collectors中的toMap(Function,Function,BinaryOperator)方法不适用于参数((s) > {},int,Integer :: sum)

The method toMap(Function, Function, BinaryOperator) in the type Collectors is not applicable for the arguments (( s) -> {}, int, Integer::sum)

顺便说一下,我知道这个解决方案:

By the way, I know about that solution:

Map<String, Long> counter2 = stream.collect(Collectors.groupingBy(s -> s, Collectors.counting()));

所以我有两个问题:


  1. 我的第一种方法有什么错误?

  2. 如何实现这样的计数器?

EDIT:我自己解决了第一个问题:

I solved the first question by myself:

Map<String, Integer> counter1 = stream.collect(Collectors.toMap(s -> s, s -> 1, Integer::sum)); 

Java正在等待第二个参数。

Java is expecting a function as second argument.

推荐答案

确实有几种方法。您没有提到的是 .collect(groupingBy(x - > x,summingInt(x - > 1)));

There are indeed several ways to do it. The one you haven't mentioned is .collect(groupingBy(x -> x, summingInt(x -> 1)));

性能有一些差异。

如果每个桶中的对象非常少,则方法1将处于最佳状态。在每个桶只有1个对象的理想情况下,您将立即结束最终映射,无需修改条目。

Approach #1 is going to be at its best if there are very few objects per bucket. In the ideal case of only 1 object per bucket, you end up with the final map right away with no need to modify the entries. In the worst case of having a very large number of repeated objects, it will have to do a lot of boxing/unboxing.

方法#2依赖于 counting() collector,它没有指定它应该如何做计数。当前实现转发到减少,但可能会改变。

Approach #2 relies on counting() collector, which doesn't specify exactly how it should do the counting. The current implementation forwards to reducing but that might change.

summingInt 方法将累积 int 中的计数,而不是整数,因此不需要任何装箱/取消装箱。

The summingInt approach will accumulate the count in int rather than Integer and thus will not require any boxing/unboxing. It will be at its best if objects repeat a very large number of times.

对于选择哪一个,最好是编写清晰度并优化,当它变成必要。对我来说, groupingBy(x-> x,counting())表达的意图最清楚,所以这是我赞成的。

As for which one to choose, it is best to code for clarity and optimize when it becomes necessary. To me, groupingBy(x->x, counting()) expresses the intent most clearly, so that's the one I would favor.

这篇关于计数流的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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