Java计数数组中每个项的出现次数 [英] Java count occurrence of each item in an array

查看:200
本文介绍了Java计数数组中每个项的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有任何方法来计算数组上每个项目的出现次数?

Is there any method for counting the occurrence of each item on an array?

假设我有:

String[] array = {"name1","name2","name3","name4", "name5"};

这里的输出将是:

name1 1
name2 1
name3 1
name4 1
name5 1

如果我有:

String[] array = {"name1","name1","name2","name2", "name2"};

输出将是:

name1 2
name2 3

推荐答案

您可以使用 MultiSet

You could use a MultiSet from Google Collections/Guava or a Bag from Apache Commons.

如果你有一个集合而不是一个数组,你可以使用 addAll )将所有内容添加到上述数据结构中,然后对每个值应用 count()方法。 SortedMultiSet SortedBag 将按定义的顺序为您提供项目。

If you have a collection instead of an array, you can use addAll() to add the entire contents to the above data structure, and then apply the count() method to each value. A SortedMultiSet or SortedBag would give you the items in a defined order.

Google Collections实际上具有非常方便的从数组到 SortedMultiset 的方法。

Google Collections actually has very convenient ways of going from arrays to a SortedMultiset.

这篇关于Java计数数组中每个项的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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