Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circumventing the null check while populating a HashMap

Tags:

java

hashmap

While inserting into a hashmap, do I always have to check if there is a null value corresponding to the key being inserted?

For instance, if I want to keep track of the number of times a character occurs in a word, using a hashmap, do i always have to do:

if(hashMap.containsKey(ch)){
    hashMap.replace(ch, 1+hashMap.get(ch));    
}
else{
    hashMap.put(ch, 1);    
}

Or is there a function that can handle this for me?

like image 940
rahs Avatar asked Dec 22 '18 12:12

rahs


Video Answer


1 Answers

Use merge.

hashMap.merge(ch, 1, (left, right) -> left + right);

or using a method reference:

 hashMap.merge(ch, 1, Math::addExact);
  • If the specified key (ch in this case) is not already associated with a value or is associated with null, associates it with the given non-null value (1 in this case).
  • if the specified key is associated with a non-null value it then replaces the associated value with the results of the given remapping function (left, right) -> left + right.
like image 53
Ousmane D. Avatar answered Oct 23 '22 18:10

Ousmane D.