Map getOrDefault VS getOrUseSupplier

Tags: , ,



I am starting to learn lambdas and i do not understand why java Map has:

getOrDefault(Object key, V defaultValue)

and not(working just the same, but if value is absent, then defaultValue will be taken from supplier):

getOrUseSupplier(Object key, Supplier<V> defaultValue)

Adventages i currently see of current solution:

  • defaultValue does not have to be a final/effectively final value
  • looks simpler & no need to know lambda syntax

Disadventages:

  • If while using getOrDefault we put new object creation, it will be created and passed to GC immidietely(while using supplier, it will not be created at all).

I would like to know if there is any more disadventages of using & having getOrDefault rather than getOrUseSupplier. Could you also tell me if anywhere in java libraries, there is method like this:

static <V> V getOrUseSupplier(Map<?, V> map, Object key, Supplier<V> supplier)

that tries to take Value from map, and if it does not exist then takes value from Supplier.

Answer

The closest equivalent of getOrUseSupplier() in Map is named computeIfAbsent() which allows for the value to be computed using the key, giving more flexibility than if it only took a Supplier. It also stores the computed value in the Map, unlike getOrDefault. This is because they have distinct use cases and are not really related. While getOrDefault is usually used to return a “safe” non-null default value (such as returning empty string instead of a null) indicating that something should be in the map, computeIfAbsent() implies that something must be in the map, and if it’s not, it needs to be created or otherwise the internal state of the program is not correct.

The following example ignores the key and just uses the supplier’s value.

public static <V,T> V getOrUseSupplier(Map<T, V> map, T key, Supplier<V> supplier) {
    return map.computeIfAbsent(key, k -> supplier.get());
}


Source: stackoverflow