It's always a good idea to look at the Google Collections Library for this kind of thing. In this case a Multiset will do the trick:
Multiset bag = Multisets.newHashMultiset();
String word = "foo";
bag.add(word);
bag.add(word);
System.out.println(bag.count(word)); // Prints 2
There are Map-like methods for iterating over keys/entries, etc. Internally the implementation currently uses a HashMap<E, AtomicInteger>
, so you will not incur boxing costs.