Skip to content

Instantly share code, notes, and snippets.

@nipafx
Created November 7, 2015 12:54
Show Gist options
  • Save nipafx/8e8797c6ad7fa9479a14 to your computer and use it in GitHub Desktop.
Save nipafx/8e8797c6ad7fa9479a14 to your computer and use it in GitHub Desktop.
How nice would 'Map.getAsOptional' be?
package org.codefx.lab.optional;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class MapGet {
private final MapWithGetAsOptional<Integer, String> map = new HashMapWithGetAsOptional<>();
public Optional<MessageFormat> getFormat_if(int index) {
if(map.containsKey(index))
return Optional.of(new MessageFormat(map.get(index)));
else
return Optional.empty();
}
public Optional<MessageFormat> getFormat_ternary(int index) {
return map.containsKey(index)
? Optional.of(new MessageFormat(map.get(index)))
: Optional.empty();
}
public Optional<MessageFormat> getFormat_optionalOf(int index) {
return Optional.ofNullable(map.get(index))
.map(MessageFormat::new);
}
public Optional<MessageFormat> getFormat_optional(int index) {
return map.getAsOptional(index)
.map(MessageFormat::new);
}
interface MapWithGetAsOptional<K, V> extends Map<K, V> {
default Optional<V> getAsOptional(Object key) {
return Optional.ofNullable(get(key));
}
}
class HashMapWithGetAsOptional<K, V> extends HashMap<K, V> implements MapWithGetAsOptional<K, V> {
// nothing to do here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment