Answer the question
In order to leave comments, you need to log in
How to check if a given element is in an enum?
Good afternoon! The question arose:
Is there some simple way to check whether an element belongs to an enumeration?
Or do you need to write a separate function in each enam for this?
For example:
import java.util.Scanner;
public class Main {
enum TestEnum {
One(1), Two(3), Three(3);
private int code;
TestEnum(int code) {
this.code = code;
}
}
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
System.out.println("n in TestEnum?");
}
}
Answer the question
In order to leave comments, you need to log in
Java 8+
import java.util.Arrays;
import java.util.Scanner;
public class Main {
enum TestEnum {
One(1), Two(2), Three(3);
private int code;
TestEnum(int code) {
this.code = code;
}
}
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
boolean isPresent = Arrays.stream(TestEnum.values()).anyMatch(element -> element.code == n);
System.out.println("n in TestEnum? " + isPresent);
}
}
the class Enum
has a static method to find out
import java.lang.Enum;
import java.lang.IllegalArgumentException;
public class EvalEnum {
enum MyEnum {
One(1), Two(2), Three(3);
private int code;
MyEnum(int code) {
this.code = code;
}
}
public static void main(String[] args) {
System.out.println(
String.format("%s in MyEnum? %b", args[0], isPresent(args[0])));
}
private static boolean isPresent(String data) {
try {
Enum.valueOf(MyEnum.class, data);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
java EvalEnum One
One in MyEnum? true
java EvalEnum Zero
Zero in MyEnum? false
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question