Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hashmap custom override value when duplicate key occurred

Tags:

java

hashmap

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

like image 927
LMK IND Avatar asked Feb 02 '26 19:02

LMK IND


2 Answers

In Java 8 you can take a look at Map.computeIfPresent() method:

hashMap.computeIfPresent(aKey, (k, v) -> v + 1);
like image 169
vania-pooh Avatar answered Feb 05 '26 08:02

vania-pooh


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));
     } 
like image 28
Puce Avatar answered Feb 05 '26 09:02

Puce