Get Enum constant by value

Viewed 367

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.)

1 Answers

You can pass it as a Predicate:

public static <E extends Enum<?>> Optional<E> getEnumByValue(Class<E> enumClass, Predicate<E> predicate) {
    return Arrays.stream(enumClass.getEnumConstants())
            .filter(predicate)
            .findFirst();
}

(Note: the method should actually return an Optional<E>)

If all enums have ids, you can still implement a common interface:

interface Identifiable {
    int getId();
}

enum PhoneType implements Identifiable {
    ...
}

public static <E extends Enum<?> & Identifiable> Optional<E> getEnumById(Class<E> enumClass, int id) {
    return Arrays.stream(enumClass.getEnumConstants())
            .filter(e -> e.getId() == id)
            .findFirst();
}

Optional<PhoneType> phone = getEnumById(PhoneType.class, phoneTypeId);
Related