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);
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).(left, right) -> left + right
. 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