Generic Filter for enum

ArunM :

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))
Ravindra Ranwala :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73203&siteId=1