从 ArrayList 中获取重复项的数量 [英] Get number of duplicates from ArrayList
问题描述
例如,假设我有一个 ArrayList
可以包含以下值:
For example, say I have an ArrayList
that could contain the following values:
x
x
x
y
y
现在我要检索的是 x
和 x
的数量,我希望能够区分我所拥有的,或者 x
或 y
因为实际上,我可以在 ArrayList 中有任何对象,而且我必须能够区分它们.
Now what I want to retrieve is the number of x
and x
and I want to be able to differentiate what I have, either x
or y
because in actuality, I could have any object in the ArrayList and I have to be able to tell them apart.
我想做的是首先将 ArrayList
转换为 LinkedHashSet
,这将保持排序并删除重复项,因此我只有 x
和 y
但是我如何获得每个的数量并将其与正确的元素相关联?
What I was thinking of doing was first converting the ArrayList
into a LinkedHashSet
, which would keep the ordering and remove the duplicates so I would just have x
and y
But how would I get the number of each and associate it with the proper element?
总的来说,我想要做的是能够编写一个 toString
方法,让我输出:
Overall what I want to do is to be able to write a toString
method that will let me output:
x3y2
但不知道 x
和 y
是元素,因为它们可能是其他类似 z
或 w代码>.
But without knowing that x
and y
are the elements because they could have been something else like z
or w
.
推荐答案
查看 google guava 中的 Multiset:http://docs.guava-libraries.googlecode.com/git-history/v11.0.2/javadoc/com/google/common/collect/Multiset.html
Check out the Multiset in google guava: http://docs.guava-libraries.googlecode.com/git-history/v11.0.2/javadoc/com/google/common/collect/Multiset.html
示例:
Multiset<String> strings = HashMultiset.create(arrayList);
int countX = strings.count("x"); // the count of x
可以在 Guava wiki 上找到更多示例.
More examples can be found on the Guava wiki.
这篇关于从 ArrayList 中获取重复项的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!