Write a Java method to check if a given string matches any value in a given enum.
Your method will take two parameters, one a string and one an enum, and return true if the string representation of any of the enum's elements matches the given string, or false otherwise. Note that your method should still function normally if the String parameter is null, and that you aren't allowed to use any external libraries.
Test cases:
public enum E { A, B, C; }
public enum F { X, Y, Z; }
check("a", E.A); // is false (because "A" is uppercase)
check(null, E.A); // is false
check("C", E.A); // is true
check("X", F.X); // is true
check(null, F.X); // is false
check("y", F.X); // is false
The method has access (as a solver correctly understood) to a generic type E that has the only bound that "E extends Enum(E)".
Reference implementation (Ungolfed):
boolean <E extends Enum<E>> check(String s, E e){
for(E ex : e.getDeclaringClass().getEnumConstants())
if(ex.toString().equals(s)) return true;
return false;
}
Another possible implementation (due to a solution) is (Ungolfed):
public static <E extends Enum<E>> boolean check(String s, E e){
return java.util.stream.Stream.of(e.getDeclaringClass().getEnumConstants()).anyMatch(x->x.name().equals(s));
}
What I'm looking for is the shortest thing I could put after return (or, as a solutor did, after "(String s,E e)->)".
This is code-golf, so fewest bytes wins!
trueis allowed. \$\endgroup\$trueif the string is equal to the string representation of any value in the enum class, andfalseotherwise.nullstrings should also result infalse." Remove the "shortest code wins" part too; tips questions are not competitions. \$\endgroup\$boolean c(String, E)then "given" means two different things in the first sentence of the question. Other interpretations would lead to signaturesboolean c(String, Enum)orboolean c(String, Class<? extends Enum>). The comment above that you "prefer if you don't make assumptions on the classE" suggests that you want the second or third signature, but the reference implementation uses the first. 2. It's confusing to ask for return values ofTrueandFalse\$\endgroup\$