I recently had the same problem and used the solution provided by Harry Joy. That solution only works with with zero-based enumaration though. I also wouldn't consider it save as it doesn't deal with indexes that are out of range.
The solution I ended up using might not be as simple but it's completely save and won't hurt the performance of your code even with big enums:
public enum Example {
UNKNOWN(0, "unknown"), ENUM1(1, "enum1"), ENUM2(2, "enum2"), ENUM3(3, "enum3");
private static HashMap<Integer, Example> enumById = new HashMap<>();
static {
Arrays.stream(values()).forEach(e -> enumById.put(e.getId(), e));
}
public static Example getById(int id) {
return enumById.getOrDefault(id, UNKNOWN);
}
private int id;
private String description;
private Example(int id, String description) {
this.id = id;
this.description= description;
}
public String getDescription() {
return description;
}
public int getId() {
return id;
}
}
If you are sure that you will never be out of range with your index and you don't want to use UNKNOWN
like I did above you can of course also do:
public static Example getById(int id) {
return enumById.get(id);
}