An enum is a special class in Java that represents a group of constants. In this short tutorial, we are going to present how to get enum value using String.
2. The problem: Get enum using String value
Let's say we have the following enum
We want to find the enum value of a String, for example, "A" which would be
3. Solution1: Use
This method returns the enum with the specified name. The name must match exactly an identifier. For example to get
Alphabet.A we need to use
Note that if the specified enum type has no constant with the specified name the
IllegalArgumentException will the thrown.
This could happen for:
Alphabet.valueOf("A ")- note space at the end,
Alphabet.valueOf("9")- no such contant in
Alphabet.valueOf("a")- method is case sensitive.
4. Solution2: Filtering enum values
You can also manually filter enum values from specified type like in the following example:
In this example we used
String.equalsIgnoreCase(...) to compare specified String with enum values in case-insensitive way.
Now to find
Alphabet.A we can use this method like in the following snippet:
al variable will be equal to
5. Solution3: Checking enum values without throwing an exception
To check if enum contains constant
A without throwing an exception we can use
In the following code we used
Enums utility class from
getIfPresent(...) method will return
Alphabet doesn't have
You can also implement this method on your own in Plain Java: