Java Get Enum Value by String
Tags: Enum
In this Java tutorial, we learn how to find the enum value by the name String in Java programming language.
How to search enum value by name in Java
For example, we have an enum named UserStatus as below.
public enum UserStatus {
ACTIVE,
DELETED,
DISABLED,
BLOCKED;
}
In the following Java code, we implement a new static method named findByName(String name) to return UserStatus enum value from a given name String.
public static UserStatus findByName(String name) {
for (UserStatus userStatus : values()) {
if (userStatus.name().equalsIgnoreCase(name)) {
return userStatus;
}
}
return null;
}
Finally we have the UserStatus enum definition as the following Java code.
UserStatus.java
public enum UserStatus {
ACTIVE,
DELETED,
DISABLED,
BLOCKED;
/**
* Find UserStatus by name String
* @param name
* @return
*/
public static UserStatus findByName(String name) {
for (UserStatus userStatus : values()) {
if (userStatus.name().equalsIgnoreCase(name)) {
return userStatus;
}
}
return null;
}
}
In the following example Java program, we show how to use the UserStatus.findByName(String name) static method above to get enum value by name String.
UserStatusExample.java
public class UserStatusExample {
public static void main(String... args) {
// Get existing enum value
UserStatus userStatus1 = UserStatus.findByName("Deleted");
// Get non existed enum value
UserStatus userStatus2 = UserStatus.findByName("Inactive");
System.out.println("Deleted UserStatus: " + userStatus1);
System.out.println("Inactive UserStatus: " + userStatus2);
}
}
Deleted UserStatus: DELETED
Inactive UserStatus: null
Happy Coding 😊