A suggestion: Map.checkAndGet
Boaz Nahum
boaznahum at gmail.com
Tue Oct 30 08:25:37 PDT 2012
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