I have tried looking around for a while but I can't find a concrete answer and still am having some trouble understanding exactly what the compute
method for HashMap
does.
The way I understand it at the moment is that compute
will allow you to manipulate the value but not set it to a new value (like where the garbage collector will have to get rid of the old object) while put
will just get rid of the old object and set it (like going x = new Something).
If my understanding of this is wrong, please tell me, but regardless, is the compute
method more efficient in general? Should I use this over put
whenever possible or is it only used in certain situations?
Use put
if you want to set a new value unconditionally. Use compute
if you want to compute a new value based on the existing value in the map. You have the option of either changing it to a new value or removing it from the map.
The documentation for compute
states that:
The default implementation is equivalent to performing the following steps for this map:
V oldValue = map.get(key); V newValue = remappingFunction.apply(key, oldValue); if (newValue != null) { map.put(key, newValue); } else if (oldValue != null || map.containsKey(key)) { map.remove(key); } return newValue;
It's more complicated than a simple put
:
get
to retrieve the current value.put
to overwrite the old value or remove
to remove it depending on whether the new value is null or not.Since ultimately it ends up calling put
, compute
has more steps and is slower. If put
meets your needs—you don't care what's in the map, you just want to set a key to a value—use put
.
TL;DR
Yes, it is more efficient to use compute, instead of get() and put().
Longer version
By using a combination of compute
, computeIfPresent
computeIfAbsent
etc, you can do EXACTLY the same things using compute method as you can do with get and put. (In fact prior to JDK 8, there was no compute and lambda, but we were all able to "get by" without any large gaping holes in our coding lives, although admittedly, the things got better with lambda.)
But the main advantages of using compute method is:
So, between 2 and 3, there are good reasons to use compute.
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