Incrementing Integers in Map I have a HashMap&lt;Token, Integer&gt;, which counts occurrences of Token. Each time Token is found, the value in the map should be incremented.

Map&lt;Token, Integer&gt; occurrences = new HashMap&lt;Token, Integer&gt;();
// ...

public void tokenFound(Token token) {

    Integer numberOfOccurs = occurrences.get(token);
    Integer newNumberOfOccurs = new Integer((numberOfOccurs == null) ? 1 : numberOfOccurs.intValue() + 1);
    occurrences.put(token, newNumberOfOccurs);
}


Is there a more elegant way to do this?
You have several different options for this:

Guava

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.

Java 8

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) -&gt; oldValue + one);


Or this:

occurrences.compute(token, (tokenKey, oldValue) -&gt; oldValue == null ? 1 : oldValue + 1);


Note that as of Java 7, you can initialize the map with the "diamond operator":

Map&lt;Token, Integer&gt; occurrences = new HashMap&lt;&gt;();


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);


More specifically:


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.