Last active
October 23, 2016 16:22
-
-
Save justintuchek/162dd3845ded74153265042d68e95d73 to your computer and use it in GitHub Desktop.
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 com.company.util; | |
public interface IndexValue<Source, Value> { | |
Value get(Source source); | |
} |
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 com.company.util; | |
import com.sun.istack.internal.Nullable; | |
import java.util.HashMap; | |
import java.util.Map; | |
public final class ReverseEnumIndex<Key, Value extends Enum<Value>> { | |
private final Map<Key, Value> map; | |
@Nullable | |
public Value get(Key key) { | |
return map.get(key); | |
} | |
private ReverseEnumIndex(Builder<Key, Value> builder) { | |
this.map = builder.map; | |
for(Value value : builder.enumConstants) { | |
map.put(builder.indexValue.get(value), value); | |
} | |
} | |
public static <Value extends Enum<Value>> ReverseEnumIndex<Integer, Value> ordinalIndex(Class<Value> source) { | |
return new Builder<Integer, Value>(source, new IndexValue<Value, Integer>() { | |
@Override | |
public Integer get(Value value) { | |
return value.ordinal(); | |
} | |
}).build(); | |
} | |
public static <Value extends Enum<Value>> ReverseEnumIndex<String, Value> nameIndex(Class<Value> source) { | |
return new Builder<String, Value>(source, new IndexValue<Value, String>() { | |
@Override | |
public String get(Value value) { | |
return value.name(); | |
} | |
}).build(); | |
} | |
public static <Key, Value extends Enum<Value>> ReverseEnumIndex<Key, Value> fromSource(Class<Value> source, IndexValue<Value, Key> indexValue) { | |
return new Builder<Key, Value>(source, indexValue).build(); | |
} | |
public static final class Builder<Key, Value extends Enum<Value>> { | |
private final Value[] enumConstants; | |
private final IndexValue<Value, Key> indexValue; | |
private Map<Key, Value> map; | |
public Builder(Class<Value> source, IndexValue<Value, Key> indexValue) { | |
if(source == null || indexValue == null) { | |
throw new IllegalStateException("Enum class and IndexValue must be instantiated"); | |
} | |
enumConstants = source.getEnumConstants(); | |
this.indexValue = indexValue; | |
} | |
public Builder withMap(Map<Key, Value> map) { | |
this.map = map; | |
return this; | |
} | |
public ReverseEnumIndex<Key, Value> build() { | |
if(map == null) { | |
map = new HashMap<>(enumConstants.length); | |
} | |
return new ReverseEnumIndex<>(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment