Skip to content

Instantly share code, notes, and snippets.

@wsh wsh/OptionalMap.java
Last active Dec 25, 2015

Embed
What would you like to do?
Break the Map interface to introduce null-safety via Guava's Optional. Does not allow null entries (surprise).
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.google.common.base.Optional;
import com.google.common.collect.Maps;
public class OptionalMap<K, V> {
private final Map<K, V> map;
public OptionalMap() {
map = Maps.newHashMap();
}
public OptionalMap(final Map<K, V> map) {
this.map = map;
}
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean containsKey(final Object key) {
return map.containsKey(key);
}
public boolean containsValue(final Object value) {
return map.containsValue(value);
}
public Optional<V> get(final Object key) {
return Optional.fromNullable(map.get(key));
}
public Optional<V> put(final K key, final V value) {
Objects.requireNonNull(value);
final V original = map.get(key);
map.put(key, value);
return Optional.fromNullable(original);
}
public Optional<V> remove(final Object key) {
final V original = map.get(key);
map.remove(key);
return Optional.fromNullable(original);
}
public void putAll(final Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
Objects.requireNonNull(entry);
map.put(entry.getKey(), entry.getValue());
}
}
public void clear() {
map.clear();
}
public Set<K> keySet() {
return map.keySet();
}
public Collection<V> values() {
return map.values();
}
public Set<Map.Entry<K, V>> entrySet() {
return map.entrySet();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.