如何计算列表中的一个元素出现的次数 [英] How to count the number of occurrences of an element in a List
问题描述
我有一个的ArrayList
,一个集合类的Java,如下:
I have an ArrayList
, a Collection class of Java, as follows:
ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
正如你所看到的,动物
的ArrayList
由3 蝙蝠
元素和一个猫头鹰
元素。我在想,如果有一个在集合框架返回蝙蝠
出现的数量或是否有另一种方法来确定出现的次数的API。
As you can see, the animals
ArrayList
consists of 3 bat
elements and one owl
element. I was wondering if there is any API in the Collection framework that returns the number of bat
occurrences or if there is another way to determine the number of occurrences.
我发现,谷歌的收藏多重集
确实有返回元素出现的总次数的API。不过,这只是与JDK 1.5兼容。我们的产品目前在JDK 1.6,所以我不能使用它。
I found that Google's Collection Multiset
does have an API that returns the total number of occurrences of an element. But that is compatible only with JDK 1.5. Our product is currently in JDK 1.6, so I cannot use it.
推荐答案
我是pretty确保于类别静态频率的方法将在这里派上用场:
I'm pretty sure the static frequency-method in Collections would come in handy here:
int occurrences = Collections.frequency(animals, "bat");
这就是我会做也无妨。我是pretty肯定这是JDK 1.6直线上升。
That's how I'd do it anyway. I'm pretty sure this is jdk 1.6 straight up.
这篇关于如何计算列表中的一个元素出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!