Skip to content

Instantly share code, notes, and snippets.

@kkarad
Last active December 10, 2015 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkarad/4510871 to your computer and use it in GitHub Desktop.
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.
public interface Identifiable<T> {
T getId();
}
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