Last active
December 10, 2015 23:38
-
-
Save kkarad/4510871 to your computer and use it in GitHub Desktop.
Implementation of the ReversedEnumMap as described at: http://www.javaspecialists.co.za/archive/Issue113.html. The implementation uses google-guava as a dependency but it can be easily removed.
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
public interface Identifiable<T> { | |
T getId(); | |
} |
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
import com.google.common.base.Optional; | |
import java.util.HashMap; | |
import java.util.Map; | |
import static com.google.common.base.Preconditions.checkNotNull; | |
public final class IdentifiableEnumMap<T, V extends Enum<V> & Identifiable<T>> { | |
private Map<T, V> map = new HashMap<T, V>(); | |
public IdentifiableEnumMap(Class<V> valueType) { | |
for (V v : valueType.getEnumConstants()) { | |
map.put(v.getId(), v); | |
} | |
} | |
public Optional<V> get(T id) { | |
return Optional.fromNullable(map.get(checkNotNull(id))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment