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

Following is an example invocation of the above method

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

Can this same functionality be implemented using a Java 8 FunctionalInterface. I have tried creating a BiPredicate but am getting compiler errors when I try this.

final BiPredicate<String,Class> biPre = (string1, clazz) -> EnumSet.allOf(clazz).stream().anyMatch(e -> e.name().equals(s));
2
  • 1
    final BiPredicate<String,Class> biPre to final BiPredicate<String,Class<Animal>> biPre ? Commented Jan 22, 2019 at 4:17
  • Thats not generic. If I need to implement a validateEnum for another Enum I will need to create a new BiPredicate Commented Jan 22, 2019 at 4:24

2 Answers 2

6

Here's a one way of doing it,

final BiPredicate<String, ? super Enum<?>> biPre = (string1, enumType) -> EnumSet
        .allOf(enumType.getDeclaringClass()).stream().anyMatch(e -> e.name().equals(string1));

And here's the client code,

boolean test = biPre.test("DOG", Animal.CAT);

However passing an enum constant instead of a class literal seems a bit awkward here.

If you really need to use the type token here's what you should do,

final BiPredicate<String, Class<? extends Enum<?>>> biPre = (string1, clazz) -> Arrays
    .stream(clazz.getEnumConstants()).anyMatch(e -> e.name().equals(string1));

The client now looks like this,

boolean test = biPre.test("DOG", Animal.class);
Sign up to request clarification or add additional context in comments.

Comments

2

You have to declare the class in which the biPre is defined as generic similar to the function validateEnum.

public class Test<E extends Enum<E>> {
    BiPredicate<String,Class<E>> biPre = (string1,clazz) -> EnumSet.allOf(clazz).stream().anyMatch(e -> e.name().equals(string1));
}

Then you can test it like this:

boolean isValid = biPre.test( "DOG", (Class<E>) Animal.class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.