New methods in java.util.Map

Ethan McCue ethan at mccue.dev
Fri Oct 17 03:05:35 UTC 2025


I don't have anything intelligent to add, but I assume either

* It's a good / okay idea, not high priority
* putIfAbsent and computeIfAbsent are seen to be enough for lazy operations
* Something much more subtle and/or annoying about how it will affect the
universe of map implementations.

Either way, just so there is something concrete to talk about:

import module java.base;

public final class Maps {
    private Maps() {
    }

    private static final Object DEFAULT = new Object();

    @SuppressWarnings({"unchecked","rawtypes"})
    public static <K, V> V getOrCompute(
            Map<K, ? extends V> m,
            Object key,
            Function<? super K, ? extends V> compute
    ) {
        Object value = ((Map) m).getOrDefault(key, DEFAULT);
        if (value == DEFAULT) {
            return compute.apply((K) key);
        }
        else {
            return (V) value;
        }
    }
}

(Note the three needed casts - this might be difficult for the same reason
Map#get takes an Object and not a K)

On Thu, Oct 16, 2025 at 7:20 PM Chris Bouchard <chris at upliftinglemma.net>
wrote:

> Alberto,
>
> I believe your getOrPut methods already exist as putIfAbsent and
> computeIfAbsent, unless I'm missing a subtle difference.
>
> On Thu, Oct 16, 2025, 14:20 Alberto Otero Rodríguez <alber84ou at gmail.com>
> wrote:
>
>> Also, other two new methods might be interesting if you want to get a
>> value from a map, but if the key doesn't exist you want to insert that
>> value in the map and return it:
>>
>> default V getOrPut(Object key, V defaultValue)
>>
>> default V getOrPut(Object key,  Function<? super K, ? extends V>
>> defaultValueFunction)
>>
>
> Chris
>
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20251016/73a7f462/attachment-0001.htm>


More information about the amber-dev mailing list