Created
November 7, 2015 12:54
-
-
Save nipafx/8e8797c6ad7fa9479a14 to your computer and use it in GitHub Desktop.
How nice would 'Map.getAsOptional' be?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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