HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Incrementing Integers in Map

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
integersmapincrementing

Problem

I have a HashMap, which counts occurrences of Token. Each time Token is found, the value in the map should be incremented.

Map occurrences = new HashMap();
// ...

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?

Solution

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


Or this:

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


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.

Code Snippets

occurrences.merge(token, 1, (oldValue, one) -> oldValue + one);
occurrences.compute(token, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);
Map<Token, Integer> occurrences = new HashMap<>();
Integer previousValue = occurrences.get(token);
occurrences.put(token, previousValue == null ? 1 : previousValue + 1);

Context

StackExchange Code Review Q#57078, answer score: 40

Revisions (0)

No revisions yet.