Java计数数组中每个项的出现次数

编程入门 行业动态 更新时间:2024-10-17 15:34:21
本文介绍了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计数数组中每个项的出现次数

本文发布于:2023-11-30 17:32:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650906.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数数   组中   次数   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!