A suggestion: Map.checkAndGet
Mike Duigou
mike.duigou at oracle.com
Tue Oct 30 09:49:22 PDT 2012
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