简体   繁体   中英

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

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

Java 8 way:

Arrays.stream(UserType.values())
      .collect(Collectors.toMap(UserType::getName, Function.identity()))

Understandably store it in a variable :)

我认为在地图中使用 Enum 作为键的最简单方法是使用 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

With Java 8 stream api and assignment immediately to the desired structure:

HashMap<String, UserType> collect = Arrays.stream(UserType.values())
    .collect(Collectors.toMap(
            UserType::getName,
            Function.identity(),
            (prev, next) -> next, HashMap::new)
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM