user1141584
user1141584

Reputation: 619

HashMap group by (Java)

Is there a way we can group by Key and add the value in a HashMap in Java

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    map.put("A", 2);
    map.put("A", 3);
    map.put("B", 4);
    map.put("A", 5);
    map.put("B", 4);    

The result is

   A = 10
   B = 8

Any help would be helpful !!!

Upvotes: 3

Views: 7166

Answers (5)

Zach Langley
Zach Langley

Reputation: 6786

Something like this should work:

public void incrementValue(HashMap<String, Integer> map, String key, int value) {
    Integer old = map.get(key);
    if (old == null) {
        map.put(key, value);
    } else {
        map.put(key, value + old);
    }
}

Upvotes: 5

Anton Bessonov
Anton Bessonov

Reputation: 9813

See answer on Java algorithm to track parts of aggregated values:

private static class MutableValue {
    double value;
    public MutableValue(double value) {
        this.value = value;
    }
    public void add(double value) {
        this.value += value;
    }
}

MutableValue value = sourceNameMap.get(ticketId);
if (oldValue == null) {
    sourceNameMap.put(new MutableValue(entryValue));
} else {
    value.add(entryValue);
}

Upvotes: 0

AlexR
AlexR

Reputation: 115328

Write utility method that does this:

Map<String, Integer> map = new HashMap<>();
.........
public void putAndIncrement(String key, int value) {
    Integer prev = map.get(key);
    Integer newValue = value;
    if (prev != null) {
        newValue += prev.intValue();
    }
    map.put(newValue);
}

Upvotes: 4

Udo Held
Udo Held

Reputation: 12538

You shouldn't use a hashmap.

map.put("A", 2);
map.put("A", 3);

The second put overwrites the first put. Use a list. Loop through it and do the addition yourself.

Upvotes: 3

Jayy
Jayy

Reputation: 2436

You can group in this way

HashMap<String, ArrayList<Integer>>

Whenever you see A keep adding the values into its ArrayList

Upvotes: 2

Related Questions