How to reverse lookup enum by value
While creating enums in java, programmers can store additional information along with enum name. For example users can declare value field in the enum constructor to store additional values. In below example, int value is stored along with enum.
Common use-case where reverse lookup is required
Once value is stored in enum constant, programmers often run into a situation where enum is required based on the value. One of the common use-case is when enum value is stored in database and while querying this value is to be converted back into Enum to be used in the application. For example in above example value “1” is stored in database and in select query “1” is to be converted into Enum to be stored in the data transfer object.
Different ways to reverse lookup enum based on value
Java’s abstract class Enum.java provides values() method which returns all enums constants stored in enum. Using this enum constants array, Enums can be reversed lookup based on value using following ways –
1. Static attribute containing map keyed by value – In Enum, create a map in static block keyed by values. It can be done by iterating values array and put them in a map. Once all enum contants are stored in a map, you can create a static method to return map based on the value (getEnum method in below snippet).
As you see in above example, NumberEnum for value “5” couldn’t be found and hence null is returned back.
2. Static getEnum method to iterate values and return map Instead of iterating over values in static block and storing them in static map, getEnum method can iterate over values at runtime and return the enum based on passed in value. This approach might take more time if number of enum constants are more. We will discuss about performance in next section in detail.