How to count the number of occurrences of an element in a List

MM. picture MM. · Feb 3, 2009 · Viewed 341.8k times · Source

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");

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.

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.

Answer

Lars Andren picture Lars Andren · Mar 17, 2010

I'm pretty sure the static frequency-method in Collections would come in handy here:

int occurrences = Collections.frequency(animals, "bat");

That's how I'd do it anyway. I'm pretty sure this is jdk 1.6 straight up.