A suggestion: Map.checkAndGet

Zhong Yu zhong.j.yu at gmail.com
Wed Oct 31 08:44:11 PDT 2012


How can we add any default method to an interface, since its behavior
might conflict with some unknown subclass' unknown additional
contracts?

On Tue, Oct 30, 2012 at 11:49 AM, Mike Duigou <mike.duigou at oracle.com> wrote:
> Unfortunately such a method would introduce non-atomic behaviour for synchronized maps so we can't add it.
>
> Mike
>
> On Oct 30 2012, at 08:25 , Boaz Nahum wrote:
>
>> The pattern
>> map.containsKey(k) ? map.get() : othervAlue
>> (walks on tree twice)
>>
>> repeats itself so many times, as in Mappers:
>>
>> public static <T, U> Mapper<T, U> forMap(Map<? super T, ? extends U> map,
>> U defaultValue) {
>>        Objects.requireNonNull(map);
>>
>>        return t -> map.containsKey(t) ? map.get(t) : defaultValue;
>> }
>>
>>
>> Now that we have 'default methods', we can add to Map:
>>
>> NullableOptional<V> checkAndget(K key) default {
>>
>>        if (containsKey(key)) {
>>            return new NullableOptional<>(get(key));
>>        } else {
>>            return NullableOptional.empty();
>>        }
>>    }
>>
>> **and** implement it in Map implementation in such way that will walk on
>> tree only once.
>> (Assume creating instance of NullableOptional is more  efficient )
>>
>> forMap becomes:
>>
>> public static <T, U> Mapper<T, U> forMap(MyMap<? super T, ? extends U> map,
>> U defaultValue) {
>>        Objects.requireNonNull(map);
>>
>>
>>        return t -> {
>>            NullableOptional<? extends U> o = map.checkAndget(t);
>>            return o.isPresent() ? o.get() : defaultValue;
>>            //return o.orElse(defaultValue);
>>        };
>>    }
>>
>
>


More information about the lambda-dev mailing list