Elegant way of counting occurrences in a java collection

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.


I know this is an old question, but I've found a more elegant way in Java 8 for counting these votes, hope you like it.

Map<String, Long> map = a.getSomeStringList()
            .stream()
            .collect(Collectors.groupingBy(
                    Function.identity(),
                    Collectors.counting())
            );

Any error, just comment.


Now let's try some Java 8 code:

static public Map<String, Integer> toMap(List<String> lst) {
    return lst.stream()
            .collect(HashMap<String, Integer>::new,
                    (map, str) -> {
                        if (!map.containsKey(str)) {
                            map.put(str, 1);
                        } else {
                            map.put(str, map.get(str) + 1);
                        }
                    },
                    HashMap<String, Integer>::putAll);
}
static public Map<String, Integer> toMap(List<String> lst) {
    return lst.stream().collect(Collectors.groupingBy(s -> s,
                                  Collectors.counting()));
}

I think this code is more elegant.