You have several different options for this:
Google's Guava Library introduces the idea of a Multiset which is capable of counting the occurrences, and also provides a couple of other features.
If you are using Java 8 (which I highly recommend if you have the ability to do so), your
tokenFound method can simply be this:
occurrences.merge(token, 1, (oldValue, one) -> oldValue + one);
occurrences.compute(token, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);
Note that as of Java 7, you can initialize the map with the "diamond operator":
Map<Token, Integer> occurrences = new HashMap<>();
Without Java 8, no libraries
If you are unable to use Java 8 and don't want to add Guava as a third party library to your project, there are a small part you can do to simplify your existing code:
Integer previousValue = occurrences.get(token);
occurrences.put(token, previousValue == null ? 1 : previousValue + 1);
- Using the
new Integer constructor is not necessary, Java automatically uses boxing to do this. For Integer values close to zero, this will actually save you a little bit because Java keeps some integers cached.
- You don't need the
newNumberOfOccurs variable as it's only used once.