Details
-
Documentation
-
Status: Closed
-
Minor
-
Resolution: Fixed
-
None
-
None
-
None
Description
public static <K, V> V get(Map<K, V> map, K key, V defaultValue) { if (!map.containsKey(key)) { map.put(key, defaultValue); } return map.get(key); }
Above there's the get() method for ALL maps if there's more than one arguments for this. You can find that it will put the defaultValue into the map if the key doesn't hit.
It seems not to be an obvious choice for programmers, as the origin map would be CHANGED when the programmer may just want a default value.
Meanwhile, some of the implements of Map have some restrictions for the values. For example, Redisson doesn't allow null values for its RMap class. So when you're using Redisson in Groovy like this,
RMapCache<String, String> map = redissonClient.getMapCache(SOME_KEY) String cachedValue = map.getOrDefault(key, null)
it will return a NullPointerError like "map value can't be null".