如何计算List中某个元素出现的次数 [英] How to count the number of occurrences of an element in a List
问题描述
我有一个ArrayList
,Java的一个Collection类,如下:
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");
如您所见,animals
ArrayList
由 3 个 bat
元素和一个 owl
元素组成.我想知道 Collection 框架中是否有任何 API 可以返回 bat
出现的次数,或者是否有另一种方法来确定出现次数.
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.
我发现 Google 的 Collection Multiset
确实有一个 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.
推荐答案
我很确定 Collections 中的静态频率方法在这里会派上用场:
I'm pretty sure the static frequency-method in Collections would come in handy here:
int occurrences = Collections.frequency(animals, "bat");
反正我就是这么做的.我很确定这是 jdk 1.6 直接.
That's how I'd do it anyway. I'm pretty sure this is jdk 1.6 straight up.
这篇关于如何计算List中某个元素出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!