Kutubek Kylychbekov
Kutubek Kylychbekov

Reputation: 45

How to increment a value, given a key in a java hashmap?

If I have the following:

public enum Attribute {
     ONE, TWO, THREE
}

private Map<String, Integer> mAttributesMap = new HashMap<>();

mAttributesMap.put(Attribute.ONE.name(), 5);
mAttributesMap.put(Attribute.TWO.name(), 5);

So how can I get the key of mAttibutesMap? And how to increment it?

Upvotes: 0

Views: 10729

Answers (3)

David Geirola
David Geirola

Reputation: 632

You can not edit directly a map, but you can replace a value using:

mAttributesMap.put(Attribute.ONE.name(), 10);

Upvotes: 2

masarapmabuhay
masarapmabuhay

Reputation: 524

If you know that the key exists in the HashMap, you can do the following:

int currentValue = mAttributesMap.get(Attribute.ONE.name());
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);

If the key may or may not exist in the HashMap, you can do the following:

int currentValue = 0;
if (mAttributesMap.containsKey(Attribute.ONE.name())) {
  currentValue = mAttributesMap.get(Attribute.ONE.name());
}
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);

I hope this helps you! Thank you. Peace.

p.s. This is my updated version of David Geirola's answer on Mar 22 '18 at 8:22.

Upvotes: 1

azro
azro

Reputation: 54168

1. First you could directly use a Map<Attribute , Integer> and put like this :

mAttributesMap.put(Attribute.ONE, 5);
mAttributesMap.put(Attribute.TWO, 5);

2. To increment the value of a key, you can do as follow, get the value, and put it again with +1, because the key already exists it will just replace the existing one (keys in a map are unique) :

public void incrementValueFromKey(Attribute key){
    mAttributesMap.computeIfPresent(key, (k, v) -> v + 1);
}

3. To have a more generic solution you could do :

public void incrementValueFromKey(Attribute key, int increment){
    mAttributesMap.computeIfPresent(key, (k, v) -> v + increment);
}

Upvotes: 9

Related Questions