Easiest way to get Enum in to Key Value pair
I have defined my Enums like this.
public enum UserType {
RESELLER("Reseller"),
SERVICE_MANAGER("Manager"),
HOST("Host");
private String name;
private UserType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
What should be the easiest way to get a key-value pair form the enum values?
The output map i want to create should be like this
key = Enum(example:- HOST)
value = Host
The map I want do define is
Map<String, String> constansts = new HashMap<String, String>();
Ans: What I Did
I have created a Generic Method to access any enum and change values from that to a Map. I got this IDEA, form a code fragment fo开发者_JS百科und at here in any other thread.
public static <T extends Enum<T>> Map<String, String> getConstantMap(
Class<T> klass) {
Map<String, String> vals = new HashMap<String, String>(0);
try {
Method m = klass.getMethod("values", null);
Object obj = m.invoke(null, null);
for (Enum<T> enumval : (Enum<T>[]) obj) {
vals.put(enumval.name(), enumval.toString());
}
} catch (Exception ex) {
// shouldn't happen...
}
return vals;
}
Now, After this all I have to do is call this method with all the enum constructs and i am Done.
One More thing
To get This done i have to orverride the toString Method like this
public String toString() {
return name;
}
Thanks.
Provided you need to map from the textual values to the enum instances:
Map<String, UserType> map = new HashMap<String, UserType>();
map.put(RESELLER.getName(), RESELLER);
map.put(SERVICE_MANAGER.getName(), SERVICE_MANAGER);
map.put(HOST.getName(), HOST);
or a more generic approach:
for (UserType userType : UserType.values()) {
map.put(userType.getName(), userType);
}
Java 8 way:
Arrays.stream(UserType.values())
.collect(Collectors.toMap(UserType::getName, Function.identity()))
Understandably store it in a variable :)
You could use the values() method on the enum, giving you all possible combinations, and put that in a map using the iterator.
Map<String, UserType> map = new HashMap<String, UserType>();
for (UserType userType : UserType.values()) {
map.put(userType.name(), userType);
}
I think that the eaiest method for using an Enum as a key in a map is using an EnumMap http://download.oracle.com/javase/1,5.0/docs/api/java/util/EnumMap.html
You could use EnumMap which is a Map implementation that exclusively takes Enum as its keys.
EnumMap<UserType, String> activityMap = new EnumMap<>(UserType.class);
However, EnumMap requires the key type in the constructor.
Reference: https://www.baeldung.com/java-enum-map
精彩评论