Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Filter for enum

Following is my class

public final class Test {
enum Animal {DOG,CAT};
enum COLOR {RED,YELLOW};

class Meaningless {
    String animal,color;
}
public void filter(List<Meaningless> meaninglesses){
    meaninglesses.stream()
            .filter(meaningless -> {
                try {
                    Animal.valueOf(meaningless.animal);
                    return true;
                }catch(Exception e){
                    return false;
                }
            })
            .filter(meaningless -> {
                try {
                    COLOR.valueOf(meaningless.color);
                    return true;
                }catch(Exception e){
                    return false;
                }
            })
            .collect(Collectors.toList());
}

}

The 2 iterations of filter methods essentially filters out the invalid enum types. How can I remove the code duplication from this ? The check should be generic enough so that I dont have to change the isValidEnum when there is a new enum introduced.

Ideally I would like to do something like

 meaninglesses.stream()
            .filter(meaningless -> isValidEnum(meaningless.animal,Animal.class))
            .filter(meaningless -> isValidEnum(meaningless.color,COLOR.class))
like image 556
ArunM Avatar asked Feb 11 '26 20:02

ArunM


2 Answers

The following utility method should do the trick here,

public static <E extends Enum<E>> boolean validateEnum(Class<E> clazz, String s) {
    return EnumSet.allOf(clazz).stream().anyMatch(e -> e.name().equals(s));
}

And here's how your client code looks in practice,

boolean isValid = validateEnum(Animal.class, "DOG");

Finally, putting it back to your context, it should be something like this.

meaninglesses.stream()
    .filter(meaningless -> validateEnum(Animal.class, meaningless.animal))
    .filter(meaningless -> validateEnum(COLOR.class, meaningless.color))
    .collect(Collectors.toList());
like image 89
Ravindra Ranwala Avatar answered Feb 13 '26 08:02

Ravindra Ranwala


Instead of reinventing the wheel, you can simply go with Apache Common EnumUtils isValidEnum(Class<E> enumClass,String enumName)

Also, isValidEnumIgnoreCase(Class<E> enumClass,String enumName) can be used to check if you need case-insensitivity.

Docs here

like image 35
Mohamed Anees A Avatar answered Feb 13 '26 09:02

Mohamed Anees A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!