Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to get Enum in to Key Value pair

Tags:

java

enums

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.

like image 927
vijay.shad Avatar asked Mar 08 '10 12:03

vijay.shad


1 Answers

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);
}
like image 62
Péter Török Avatar answered Oct 10 '22 06:10

Péter Török