Java
Enum
Programming
String Manipulation
Coding Tips

Java: check if an enum contains a given string

Codemia Knowledge Hub ·

Use Arrays.stream(MyEnum.values()).anyMatch(e -> e.name().equals(input)). Unlike Enum.valueOf(), it does not throw IllegalArgumentException for unknown values. For hot paths, build a static Set<String> or Map inside the enum once. The sections below also cover case-insensitive matching and matching on custom enum fields.

All examples use this enum:

java
public enum Status {
    PENDING, ACTIVE, INACTIVE, DELETED;
}

Stream with anyMatch

The cleanest option for a simple existence check:

java
1import java.util.Arrays;
2
3public static boolean contains(String value) {
4    return Arrays.stream(Status.values())
5                 .anyMatch(status -> status.name().equals(value));
6}
7
8// Usage
9contains("ACTIVE");    // true
10contains("active");    // false (case-sensitive)
11contains("UNKNOWN");   // false
12contains(null);        // throws NullPointerException

Null-safe version

java
1public static boolean contains(String value) {
2    return value != null && Arrays.stream(Status.values())
3                                  .anyMatch(status -> status.name().equals(value));
4}

valueOf with exception handling

Enum.valueOf() returns the constant if it exists and throws IllegalArgumentException if it does not:

java
1public static boolean contains(String value) {
2    try {
3        Status.valueOf(value);
4        return true;
5    } catch (IllegalArgumentException | NullPointerException e) {
6        return false;
7    }
8}

It works, but using exceptions for control flow is a code smell, and building the stack trace has a measurable cost when invalid values are common.

Pre-built Set for fast lookups

If you check membership often (for example when validating API requests), build a Set once and reuse it:

java
1import java.util.Arrays;
2import java.util.Set;
3import java.util.stream.Collectors;
4
5public enum Status {
6    PENDING, ACTIVE, INACTIVE, DELETED;
7
8    private static final Set<String> NAMES = Arrays.stream(values())
9            .map(Enum::name)
10            .collect(Collectors.toUnmodifiableSet());
11
12    public static boolean contains(String value) {
13        return NAMES.contains(value);
14    }
15}
16
17// Usage
18Status.contains("ACTIVE");    // true - O(1) lookup
19Status.contains("UNKNOWN");   // false - O(1) lookup
20Status.contains(null);        // throws NullPointerException

Lookups are O(1) instead of O(n), which matters for enums with many constants. A set from Collectors.toUnmodifiableSet() does not permit nulls, so its contains(null) throws NullPointerException. Add a null check before the lookup if the input can be null.

Case-insensitive matching

API input often arrives in lowercase or mixed case.

Uppercase the input

java
1public static boolean containsIgnoreCase(String value) {
2    if (value == null) return false;
3    try {
4        Status.valueOf(value.toUpperCase());
5        return true;
6    } catch (IllegalArgumentException e) {
7        return false;
8    }
9}

Stream with equalsIgnoreCase

java
1public static boolean containsIgnoreCase(String value) {
2    return value != null && Arrays.stream(Status.values())
3            .anyMatch(status -> status.name().equalsIgnoreCase(value));
4}
5
6// Usage
7containsIgnoreCase("active");   // true
8containsIgnoreCase("Active");   // true
9containsIgnoreCase("ACTIVE");   // true

Pre-built case-insensitive map

This is the fastest option:

java
1import java.util.Arrays;
2import java.util.Map;
3import java.util.function.Function;
4import java.util.stream.Collectors;
5
6public enum Status {
7    PENDING, ACTIVE, INACTIVE, DELETED;
8
9    private static final Map<String, Status> LOOKUP =
10            Arrays.stream(values())
11                  .collect(Collectors.toMap(
12                      s -> s.name().toLowerCase(),
13                      Function.identity()
14                  ));
15
16    public static Status fromString(String value) {
17        return value == null ? null : LOOKUP.get(value.toLowerCase());
18    }
19
20    public static boolean containsIgnoreCase(String value) {
21        return fromString(value) != null;
22    }
23}

Matching on custom fields

Enums often carry display names, database codes or API values:

java
1import java.util.Arrays;
2import java.util.Map;
3import java.util.function.Function;
4import java.util.stream.Collectors;
5
6public enum Status {
7    PENDING("pending", 0),
8    ACTIVE("active", 1),
9    INACTIVE("inactive", 2),
10    DELETED("deleted", 3);
11
12    private final String label;
13    private final int code;
14
15    Status(String label, int code) {
16        this.label = label;
17        this.code = code;
18    }
19
20    public String getLabel() { return label; }
21    public int getCode() { return code; }
22
23    private static final Map<String, Status> BY_LABEL =
24            Arrays.stream(values())
25                  .collect(Collectors.toMap(Status::getLabel, Function.identity()));
26
27    private static final Map<Integer, Status> BY_CODE =
28            Arrays.stream(values())
29                  .collect(Collectors.toMap(Status::getCode, Function.identity()));
30
31    public static Status fromLabel(String label) {
32        return BY_LABEL.get(label);
33    }
34
35    public static Status fromCode(int code) {
36        return BY_CODE.get(code);
37    }
38
39    public static boolean containsLabel(String label) {
40        return BY_LABEL.containsKey(label);
41    }
42}

Usage:

java
Status.fromLabel("active");        // Status.ACTIVE
Status.fromCode(2);                // Status.INACTIVE
Status.containsLabel("archived");  // false

Comparing the approaches

MethodTime ComplexityHandles nullCase-insensitiveReturns Enum Value
Stream + anyMatchO(n)Must handle manuallyWith equalsIgnoreCaseNo
valueOf + try/catchO(1) amortizedYes (catches NPE)With toUpperCaseYes
Pre-built SetO(1)No (unmodifiable set throws NPE)With lowercase keysNo
Pre-built MapO(1)Yes (returns null)With lowercase keysYes

Generic utility for any enum

To check membership across several enums, write a generic helper:

java
1import java.util.Arrays;
2
3public final class EnumUtils {
4
5    private EnumUtils() {}
6
7    public static <E extends Enum<E>> boolean contains(Class<E> enumClass, String name) {
8        return name != null && Arrays.stream(enumClass.getEnumConstants())
9                .anyMatch(e -> e.name().equals(name));
10    }
11
12    public static <E extends Enum<E>> boolean containsIgnoreCase(Class<E> enumClass, String name) {
13        return name != null && Arrays.stream(enumClass.getEnumConstants())
14                .anyMatch(e -> e.name().equalsIgnoreCase(name));
15    }
16}
17
18// Usage
19EnumUtils.contains(Status.class, "ACTIVE");              // true
20EnumUtils.containsIgnoreCase(Status.class, "active");    // true

Apache Commons Lang EnumUtils

If the project already depends on Apache Commons Lang:

java
1import org.apache.commons.lang3.EnumUtils;
2
3EnumUtils.isValidEnum(Status.class, "ACTIVE");                // true
4EnumUtils.isValidEnum(Status.class, "active");                // false
5EnumUtils.isValidEnumIgnoreCase(Status.class, "active");      // true (since Commons Lang 3.8)

Mistakes to avoid

  • Using valueOf for validation. It throws IllegalArgumentException for missing values. Exceptions for expected cases, such as validating user input, are inefficient and make debugging noisy. Use a stream or set-based check.
  • Forgetting that name() is case-sensitive. Status.valueOf("active") throws because enum names are uppercase by convention. Normalize case for user input, API payloads and config files.
  • Calling values() in a loop. values() creates a new array on every call, which adds GC pressure in hot loops. Cache it or use a pre-built Set or Map.
  • Null handling. Enum.valueOf(null) throws NullPointerException, not IllegalArgumentException. Null-check input before passing it to enum methods.
  • Assuming enum names match database or API values. Constants are usually UPPER_SNAKE_CASE, while your API may use camelCase or lowercase. Use a custom field and lookup map for external values instead of name().

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms