27 C
Bangalore
September 24, 2018
Untitled

Lookup Enum by String value

Often we come across a situation where we have to map a String value to its corresponding enum. This is my approach to solve that. Let me know what do you think.

My typical enum would be like this: Using a sample enum ‘Country’


public enum Country {
    INDIA("India"),
    CANADA("Canada"),
    US("United States Of America");

    private static final Map<String, Country> MAP;

    static {
        MAP = new HashMap<>();
        for (Country country: Country.values()) {
            MAP.put(country.toString(), country);
        }
    }

    private String name;

    Country(String s) {
        this.name = s;
    }

    @Override
    public String toString() {
        return name;
    }

    public static Country fromString(String s) {
        return MAP.get(s);
    }
}

Use Country.fromString(“India”) to get the corresponding enum.

Related posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.