Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way of counting occurrences in a java collection

Given a collection of objects with possible duplicates, I'd like end up with a count of occurrences per object. I do it by initializing an empty Map, then iterating through the Collection and mapping the object to its count (incrementing the count each time the map already contains the object).

public Map<Object, Integer> countOccurrences(Collection<Object> list) {     Map<Object, Integer> occurrenceMap = new HashMap<Object, Integer>();     for (Object obj : list) {         Integer numOccurrence = occurrenceMap.get(obj);         if (numOccurrence == null) {             //first count             occurrenceMap.put(obj, 1);         } else {             occurrenceMap.put(obj, numOccurrence++);         }     }     return occurrenceMap; } 

This looks too verbose for a simple logic of counting occurrences. Is there a more elegant/shorter way of doing this? I'm open to a completely different algorithm or a java language specific feature that allows for a shorter code.

like image 437
fo_x86 Avatar asked Jan 10 '13 14:01

fo_x86


People also ask

How do you count the number of elements in a list in Java?

The size() method of the List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container.

Which is the best collection to use in Java?

In most situations, an ArrayList is preferred over a LinkedList . LinkedList : A List backed by a set of objects, each linked to its "previous" and "next" neighbors. A LinkedList is also a Queue and Deque .

Which is faster collection in Java?

If you need fast access to elements using index, ArrayList should be choice. If you need fast access to elements using a key, use HashMap. If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).


1 Answers

Check out Guava's Multiset. Pretty much exactly what you're looking for.

Unfortunately it doesn't have an addAll(Iterable iterable) function, but a simple loop over your collection calling add(E e) is easy enough.

EDIT

My mistake, it does indeed have an addAll method - as it must, since it implements Collection.

like image 176
Tom McIntyre Avatar answered Sep 18 '22 15:09

Tom McIntyre