JavaDoc for method put of the Map interface states
If the map previously contained a mapping for the key, the old value is replaced by the specified value.
I’m looking for a Map implementation that keeps the minimal value for each key. So, that sentence should read
If the map previously contained a mapping for the key, the old value is replaced by the specified value if the new is smaller w.r.t. their natural order.
Advertisement
Answer
map.merge(key, value, Math::min)
If you must, create a class MinMap
that delegates all calls to an internal map. For more points, use Lombok delegate.
https://projectlombok.org/features/Delegate.html