Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way?

public enum Verbosity {

    BRIEF, NORMAL, FULL;

    private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();

    private Verbosity() {

        stringMap.put(this.toString(), this);

    }

    public static Verbosity getVerbosity(String key) {

        return stringMap.get(key);

    }

};

1 Answer

0 votes
by (46k points)

You're close. For arbitrary values, try something like the following:

public enum Day { 

    MONDAY("M"), TUESDAY("T"), WEDNESDAY("W"),

    THURSDAY("R"), FRIDAY("F"), SATURDAY("Sa"), SUNDAY("Su"), ;

    private final String abbreviation;

    // Reverse-lookup map for getting a day from an abbreviation

    private static final Map<String, Day> lookup = new HashMap<String, Day>();

    static {

        for (Day d : Day.values()) {

            lookup.put(d.getAbbreviation(), d);

        }

    }

    private Day(String abbreviation) {

        this.abbreviation = abbreviation;

    }

    public String getAbbreviation() {

        return abbreviation;

    }

    public static Day get(String abbreviation) {

        return lookup.get(abbreviation);

    }

}

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
2 answers
asked Nov 23, 2019 in Java by Anvi (10.2k points)
0 votes
2 answers
asked Nov 25, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...