I am new to java, I have a hashmap , i have to insert key as age and value as count, ie
HashMap<Integer,Integer> hashMap = new HashMap<Integer, Integer>();
hashMap.put(1,1);
hashMap.put(2,1);
hashMap.put(3,1);
hashMap.put(1,1); // whenever i insert this ,according to hashmap, it will override, but i want to customise like the value should be incremented , ie the value of key 1 should be 2, again if i insert with
hashMap.put(1,1); // the value of key 1 should be 3.
i want to customize overriding value , while adding duplicate key.
i have done in the following way
if(hashMap.containsValue(1)){
Integer i = hashMap.get(1);
i++;
hashMap.put(1, i);
}else{
hashMap.put(1, 1);
}
is there any best way than this ? please suggest
In Java 8 you can take a look at Map.computeIfPresent() method:
hashMap.computeIfPresent(aKey, (k, v) -> v + 1);
There are several ways to solve this issue and yours will likely be fine.
If eg. you want to minimize the number of put-operations you could create a mutable Counter class, which wraps an integer (int primitive) and provides an increment method (counter++). Then you could use it like this:
Map<Integer, Counter> ageMap;
Integer age = ....;
if(ageMap.containsValue(age)){
ageMap.get(age).increment();
}else{
ageMap.put(age, new Counter(1));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With