Explain Codes LogoExplain Codes Logo

Java: Check if enum contains a given string?

java
enum-operations
performance-optimization
best-practices
Nikita BarsukovbyNikita Barsukov·Jan 3, 2025
TLDR
public enum MyEnum { // enum constants } public static boolean isContained(String s) { // Swift and potent, but wouldn't save your soul in DarkSouls return Arrays.stream(MyEnum.values()).anyMatch(e -> e.name().equals(s)); }

Here, we leverage the power of Arrays.stream() and anyMatch(), giving a concise standard method to check if our enum MyEnum holds the string.

Fanning out the options

There are numerous, performance-efficient, and context appropriate ways to perform this operation. Below is a table of such methods:

MethodDescription
Apache Commons LangGives a simplified method: EnumUtils.isValidEnum(MyEnum.class, myValue)
HashSet utilizationBeneficial for large enums, O(1) performance
Stream API useProvides functional programming elegance: Stream.of(MyEnum.values()).anyMatch(e -> e.name().equals(myValue))

In the field, you might meet situations that demand alternative approaches.

Switch case stance

When keeping company with a switch and a string we wish to match against an enum, Apache Commons Lang is as cool as a cucumber:

if(EnumUtils.isValidEnum(MyEnum.class, myValue)) { switch(MyEnum.valueOf(myValue)) { // Paint the town red with switch case logic here } }

Notably, we've dodged the IllegalArgumentException.

Dealing with Enum.valueOf()

Don't love exceptions? Skip using Enum.valueOf(). As our wise grandma once said, "No exceptions, no worries."

Guava for optional fun

The Guava library gets our cheeky Optional token:

Optional<MyEnum> possibleEnum = Enums.getIfPresent(MyEnum.class, myValue);

Optional is your faithful hound, always indicating if the enum areas got invaded by the string.

Small enums and infrequent checking

No need calling big guns like HashSet or Streams for small enum battalions or occasional checks. A simple loop will do just fine.

Mind the traps

As you're writing your epic program, keep in mind a few things:

Dynamic enum updates

Remember, once an enum leaves the compiler, it's like a written stone - no changes. But if you break the rules, updating related HashSet or Stream collections is a bear necessity.

Case sensitivity

Enums are quite formal - they care about upper and lower case. So, "CONSTANT1" and "constant1" - total strangers in enum world.

Serialization challenges

Serialization - a blessing, making enums tricky rogues. Mind potential serialization complications with enums and HashSet involved.