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
1 answer
asked Nov 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.5k questions

29.9k answers

500 comments

99.1k users

Browse Categories

...