I want to get a specific enum based on its field value.
Enum:
public enum CrimeCategory { ASBO ("Anti Social Behaviour"), BURG ("Burglary"), CRIMDAM ("Criminal Damage And Arson"), DRUGS ("Drugs"), OTHTHEFT ("Other Theft"), PUPDISOR ("Public Disorder And Weapons"), ROBBERY ("Robbery"), SHOPLIF ("Shoplifting"), VEHICLE ("Vehicle Crime"), VIOLENT ("Violent Crime"), OTHER ("Other Crime"); private String category; private CrimeCategory (String category) { this.category = category; } public String returnString() { return category; } }
Getting a new Enum:
aStringRecivedFromJson = "Anti Social Behaviour" CrimeCategory crimeCategoryEnum; crimeCategoryEnum = CrimeCategory.valueOf(aStringRecivedFromJson);
I have been trying to work out a way for the above bring back a an enum so it can be passed stored in a HashMap
with other Crime
information.
Expected Result: ASBO
Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Example: Lookup enum by string value We then use the enum TextStyle's valueOf() method to pass the style and get the enum value we require. Since valueOf() takes a case-sensitive string value, we had to use the toUpperCase() method to convert the given string to upper case.
Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.
For reference, here is an alternative solution with a HashMap:
enum CrimeCategory { ASBO("Anti Social Behaviour"), BURG("Burglary"), CRIMDAM("Criminal Damage And Arson"), DRUGS("Drugs"), OTHTHEFT("Other Theft"), PUPDISOR("Public Disorder And Weapons"), ROBBERY("Robbery"), SHOPLIF("Shoplifting"), VEHICLE("Vehicle Crime"), VIOLENT("Violent Crime"), OTHER("Other Crime"); private static final Map<String, CrimeCategory> map = new HashMap<>(values().length, 1); static { for (CrimeCategory c : values()) map.put(c.category, c); } private final String category; private CrimeCategory(String category) { this.category = category; } public static CrimeCategory of(String name) { CrimeCategory result = map.get(name); if (result == null) { throw new IllegalArgumentException("Invalid category name: " + name); } return result; } }
Add a static method to the CrimeCategory
enum:
public static CrimeCategory valueOf(String name) { for (CrimeCategory category : values()) { if (category.category.equals(name)) { return category; } } throw new IllegalArgumentException(name); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With