FYI, the comment about compatibility was obsoleted by the addition of
default methods in Java 8.
On 1/4/2019 6:34 PM, some-java-user-99206970363698485...@vodafonemail.de
wrote:
The methods currently provided by the Map interface
(https://docs.oracle.com/javase/8/docs/api/java/util/Map.html) do not provide
an efficient way to look up nullable values. This problem would be solved if
JDK-6552529 was implemented, but that will likely not be happening since the
interface cannot be changed without breaking compatibility.
Ways to currently look up nullable values are:
* Combined ussage of `get()` and `containsKey()` -> inefficient
* Usage of `getOrDefault()` with private no-value constant, e.g.:
private static final Object NO_VALUE = new Object();
// ...
V value = map.getOrDefault(key, (V) NO_VALUE);
if (value == NO_VALUE) {
// No value
}
else {
// Value exists
}
Both solutions are not really that great, therefore it would be good to provide an
easier and (if overridden) more efficient method: default OptionalNullable<V>
getOptional(Object key) {
V value = get(key);
if (value != null || containsKey(key)) {
return OptionalNullable.of(value);
}
else {
return OptionalNullable.empty();
}
}
Where `OptionalNullable` is a new class similar to `Optional` except that null
is considered a value.
Maybe a `void ifExists(K key, Consumer<V> consumer)`, which makes the consumer
consume the value if it exists (= nullable), would be good as well to avoid creation
of `OptionalNullable` objects, though that method might (at least for performance
reasons) become obsolute when `OptionalNullable` becomes a value type.