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.

Tags : androidjava
Jacks Varghese
Over 7+ Years of Experience in Design and development in embedded and Mobile application. Expertise and Executed multiple Android SDK applications for STB (Set Top Box), Google TV, and Mobile Devices.

Leave a Reply

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