Just to be clear, you do not have to distinguish between whether the key exists in the map already or not. In other words, instead of using replace in your example, you could use put.
Of course, you do need to deal with whether or not you have a prior value that you need to include in the updated value. As others have noted, you can use the merge or compute methods.
However, if you have reasons to prefer to stick with put here are a couple of ideas for how to structure the code.
In your original code,
if(hashMap.containsKey(ch)){
hashMap.replace(ch, 1+hashMap.get(ch));
}
else{
hashMap.put(ch, 1);
}
you call containsKey and get, both of which essentially do a lookup. Why do the lookup twice?
Integer count = hashMap.get(ch);
if(count != null){
hashMap.replace(ch, 1+count);
}
else{
hashMap.put(ch, 1);
}
Instead of using replace for one case and put for the other, you can just as easily use put for both. And you can combine the cases:
Integer count = hashMap.get(ch);
if (count == null) {
count = 0;
}
hashMap.put(ch, count + 1);
I find this pattern to be very useful and it comes up a lot (at least in the applications that I work on). Here is the way I think about this:
// Get the current value.
Integer count = hashMap.get(ch);
if (count == null) {
// Business logic for initial value.
count = 0;
}
// Compute the new value (might be a bunch of business logic).
count++;
// Put the new value back.
hashMap.put(ch, count);