Difference between replace and put for HashMap

There is absolutely no difference in put and replace when there is a current mapping for the wanted key. From replace:

Replaces the entry for the specified key only if it is currently mapped to some value.

This means that if there is already a mapping for the given key, both put and replace will update the map in the same way. Both will also return the previous value associated with the key. However, if there is no mapping for that key, then replace will be a no-op (will do nothing) whereas put will still update the map.


Starting with Java 8, note that you can just use

histogramType1.merge(delay, 1, Integer::sum);

This will take care of every condition. From merge:

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null.

In this case, we are creating the entry delay -> 1 if the entry didn’t exist. If it did exist, it is updated by incrementing the value by 1.

Leave a Comment