有没有任何方法来计算数组上每个项目的出现次数?
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计数数组中每个项的出现次数
发布评论