How to reverse lookup an enum from its values in Java?
Sometime, you need to lookup an enum from its value (may be a integer, string or other types). This reverse lookup can be easily implemented by using a static java.util.Map inside your enum class. For example,
import java.util.HashMap;
import java.util.Map;
public enum Day {
SUNDAY(0),
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6);
private static final Map lookup =
new HashMap();
static {
//Create reverse lookup hash map
for(Day d : Day.values())
lookup.put(d.getDayValue(), d);
}
private int dayValue;
private Day(int dayValue) {
this.dayValue = dayValue;
}
public int getDayValue() { return dayValue; }
public static Day get(int dayValue) {
//the reverse lookup by simply getting
//the value from the lookup HsahMap.
return lookup.get(dayValue);
}
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?