Easiest way to get Enum in to Key Value pair

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);
}

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 :)

Tags:

Java

Enums