Java – generic filter for enumerations

The 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 the filtering method essentially filter out invalid enumeration types How do I remove code duplicates from? The check should be generic so that I don't have to change isvalidenum when introducing a new enumeration

Ideally, I want to do something

meaninglesses.stream()
            .filter(meaningless -> isValidEnum(meaningless.animal,Animal.class))
            .filter(meaningless -> isValidEnum(meaningless.color,COLOR.class))

Solution

The following practical methods should be 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));
}

Here's what your client code looks like in practice,

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

Finally, back to your context, it should be like this

meaninglesses.stream()
    .filter(meaningless -> validateEnum(Animal.class,meaningless.animal))
    .filter(meaningless -> validateEnum(COLOR.class,meaningless.color))
    .collect(Collectors.toList());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>