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

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

问题描述

有没有什么方法可以统计数组中每一项出现的次数?

假设我有:

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

这里的输出将是:

name1 1姓名2 1姓名3 1姓名4 1姓名5 1

如果我有:

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

输出将是:

name1 2姓名2 3

这里的输出只是为了展示预期的结果.

解决方案

您可以使用 MultiSet 来自 Google Collections/Guava 或 Bag 来自 Apache Commons.>

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

Google Collections 实际上有非常方便的方法可以将数组转换为 SortedMultiset.

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

Lets say I have:

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

Here the output will be:

name1 1
name2 1
name3 1
name4 1
name5 1

and if I have:

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

The output would be:

name1 2
name2 3

The output here is just to demonstrate the expected result.

解决方案

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

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 actually has very convenient ways of going from arrays to a SortedMultiset.

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

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