Circumventing the null check while populating a HashMap

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: