I want to create a method, which returns enum constants by it's value.
I have multiple enum classes which looks like this one (some of them have getter variables with different names):
@AllArgsConstructor
public enum PhoneType {
MOBILE("Mobile", 3),
HOME("Home", 6),
WORK("Work", 7);
@Getter
String type;
@Getter
int id;
}
I used this stream to get the enum constant:
int phoneTypeId = 3;
PhoneType phoneType = Arrays.stream(PhoneType.values())
.filter(p -> p.getId() == phoneTypeId)
.findFirst()
.orElseThrow(() -> new RuntimeException("Not able to find Enum...."));
System.out.println(phoneType.getType());
output is: "Mobile"
Now I want to create a method which will work for different enum classes. I started with something like this, but I don't know how to rewrite the filter line, to make it work for any enum class. It would be ideal to pass this "p -> p.getId() == phoneTypeId" as input parameter to this method. Any ideas?
public static <E extends Enum<?>> E getEnumByValue(Class<E> enumClass) {
return Arrays.stream(enumClass.getEnumConstants())
.filter(p -> p.getId() == phoneTypeId)
.findFirst()
.orElseThrow(() -> new RuntimeException("Not able to find Enum...."));
}
(I know that it's possible to do that if I implement interface for all enum classes, but then enum variables would have to have the same names.)