Java Check if enum contains a given string?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
To check if a Java enum contains a given string, use Arrays.stream(MyEnum.values()).anyMatch(e -> e.name().equals(input)). This avoids the IllegalArgumentException that Enum.valueOf() throws for invalid values. This article covers all the approaches, including a high-performance lookup set for hot paths, and handles the common complications like case-insensitive matching and custom enum fields.
The Enum We Will Use
All examples use this enum:
Method 1: Stream with anyMatch (Recommended)
The cleanest approach for a simple existence check:
Null-safe version
Method 2: valueOf with Exception Handling
Enum.valueOf() returns the enum constant if it exists, or throws IllegalArgumentException if it does not:
This works but using exceptions for control flow is considered a code smell. The exception is not free either: constructing the stack trace has a measurable cost, especially when called frequently with invalid values.
Method 3: Pre-built HashSet Lookup (Best for Performance)
If you check membership frequently (e.g., validating incoming API requests), build a Set once and reuse it:
This gives O(1) lookups instead of O(n) iteration. For enums with many constants, the difference is significant.
Method 4: Case-Insensitive Matching
API inputs often arrive in lowercase or mixed case. Here are your options:
Option A: Convert input to uppercase
Option B: Stream with equalsIgnoreCase
Option C: Pre-built case-insensitive map (best performance)
Method 5: Matching on Custom Fields
Enums often have custom display names, database codes, or API values:
Usage:
Method Comparison
| Method | Time Complexity | Handles null | Case-insensitive | Returns Enum Value |
| Stream + anyMatch | O(n) | Must handle manually | With equalsIgnoreCase | No |
| valueOf + try/catch | O(1) amortized | Throws NPE | With toUpperCase | Yes |
| Pre-built Set | O(1) | Yes (returns false) | With lowercase keys | No |
| Pre-built Map | O(1) | Yes (returns null) | With lowercase keys | Yes |
Generic Utility Method
If you need to check membership across multiple enums, write a generic utility:
Using Apache Commons Lang
If your project already depends on Apache Commons Lang:
Common Pitfalls
- Using valueOf for validation.
valueOfthrowsIllegalArgumentExceptionfor missing values. Using exceptions for expected flow (e.g., validating user input) is inefficient and makes debugging noisy. Use stream or set-based checks instead. - Forgetting that name() is case-sensitive.
Status.valueOf("active")throws because enum names are uppercase by convention. If your input comes from user input, API payloads, or config files, normalize the case before comparing. - Calling values() in a loop.
values()creates a new array on every call. In a hot loop, this creates GC pressure. Cache the result or use a pre-built Set/Map. - Null handling.
Enum.valueOf(null)throwsNullPointerException, notIllegalArgumentException. Always null-check your input before passing it to enum methods. - Assuming enum names match database/API values. Enum constants are typically UPPER_SNAKE_CASE, but your API might use camelCase or lowercase. Always use a custom field and lookup map rather than relying on
name()for external values.
Summary
- For simple checks, use
Arrays.stream(values()).anyMatch(e -> e.name().equals(input)). - For performance-sensitive code, build a
Set<String>orMap<String, YourEnum>as a static field inside the enum. - For case-insensitive matching, normalize to lowercase in your lookup map keys.
- For enums with custom fields (labels, codes), create dedicated
fromXxx()factory methods with pre-built maps. - Apache Commons Lang provides
EnumUtils.isValidEnum()andisValidEnumIgnoreCase()as a zero-effort alternative. - Never use
valueOf()as a validation mechanism in production code. The exception cost is not worth it.
Related reading
- Java Class that implements Map and keeps insertion order?
- java Class.isInstance vs Class.isAssignableFrom
- Java code optimization leads to numerical inaccuracies and errors
- java codility Max-Counters
- java codility training Genomic-range-query
- Java concurrency Countdown latch vs Cyclic barrier
- Java ConcurrentHashMap actions atomicity
- Java Constructor Inheritance

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.