获取副本的数目从ArrayList中 [英] Get number of duplicates from ArrayList

查看:116
本文介绍了获取副本的数目从ArrayList中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举例来说,假设我有一个的ArrayList 可能包含以下值:

For example, say I have an ArrayList that could contain the following values:

x
x
x
y
y

现在我想要检索的 X 的数量和 X ,我希望能够区分我有什么,无论是 X ,因为在现实中,我能有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 但是,我怎么会得到每一个数,并将其与关联正确的元素?结果

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 是因为他们本来是别的东西,如元素以Z 是W

But without knowing that x and y are the elements because they could have been something else like z or w.

推荐答案

退房多集在谷歌番石榴:<一href=\"http://docs.guava-libraries.google$c$c.com/git-history/v11.0.2/javadoc/com/google/common/collect/Multiset.html\" rel=\"nofollow\">http://docs.guava-libraries.google$c$c.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

更多的例子可以在番石榴维基

这篇关于获取副本的数目从ArrayList中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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