27.1 C
January 17, 2020

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 {
    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;

    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.