How to count the number of occurrences of an element in a List
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.
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.
In Java 8:
Map<String, Long> counts =
list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
This shows, why it is important to "Refer to objects by their interfaces" as described in Effective Java book.
If you code to the implementation and use ArrayList in let's say, 50 places in your code, when you find a good "List" implementation that count the items, you will have to change all those 50 places, and probably you'll have to break your code ( if it is only used by you there is not a big deal, but if it is used by someone else uses, you'll break their code too)
By programming to the interface you can let those 50 places unchanged and replace the implementation from ArrayList to "CountItemsList" (for instance ) or some other class.
Below is a very basic sample on how this could be written. This is only a sample, a production ready List would be much more complicated.
import java.util.*;
public class CountItemsList<E> extends ArrayList<E> {
// This is private. It is not visible from outside.
private Map<E,Integer> count = new HashMap<E,Integer>();
// There are several entry points to this class
// this is just to show one of them.
public boolean add( E element ) {
if( !count.containsKey( element ) ){
count.put( element, 1 );
} else {
count.put( element, count.get( element ) + 1 );
}
return super.add( element );
}
// This method belongs to CountItemList interface ( or class )
// to used you have to cast.
public int getCount( E element ) {
if( ! count.containsKey( element ) ) {
return 0;
}
return count.get( element );
}
public static void main( String [] args ) {
List<String> animals = new CountItemsList<String>();
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("bat");
System.out.println( (( CountItemsList<String> )animals).getCount( "bat" ));
}
}
OO principles applied here: inheritance, polymorphism, abstraction, encapsulation.
Alternative Java 8 solution using Streams:
long count = animals.stream().filter(animal -> "bat".equals(animal)).count();
Sorry there's no simple method call that can do it. All you'd need to do though is create a map and count frequency with it.
HashMap<String,int> frequencymap = new HashMap<String,int>();
foreach(String a in animals) {
if(frequencymap.containsKey(a)) {
frequencymap.put(a, frequencymap.get(a)+1);
}
else{ frequencymap.put(a, 1); }
}