Explain Codes LogoExplain Codes Logo

How to get an enum value from a string value in Java

java
enum-engineering
best-practices
performance
Alex KataevbyAlex Kataev·Sep 23, 2024
TLDR

Convert a String to an enum by invoking the Enum.valueOf() method. This method is case-sensitive and requires an exact match to the enum constant.

public enum Color { RED, GREEN, BLUE; } Color color = Enum.valueOf(Color.class, "GREEN");

Mismatches will throw an IllegalArgumentException.

Handling cases of case insensitivity

Often, we require string conversions to be relaxed about case. Additional error handling mechanisms can be helpful too. We can implement these flexibly by creating a custom method fromString(). This revolves around Blah.values(), an auto-generated method that gives all enum constants.

public enum Blah { A, B, C; public static Blah fromString(String s) { for (Blah blah : Blah.values()) { if (blah.name().equalsIgnoreCase(s)) { // Case-insensitive matching? Check! return blah; } } throw new IllegalArgumentException("No enum constant " + s); // Whoops, looks like you entered a typo. } }

Speeding things up with Maps

When working with large enums or when performance is a concern, use a Map<String, Enum> to enhance string-to-enum retrieval speeds. It's like a shortcut at a heavy traffic junction.

public enum Blah { A, B, C; private static final Map<String, Blah> STRING_TO_ENUM = new HashMap<>(); static { for (Blah blah : values()) { STRING_TO_ENUM.put(blah.name(), blah); // Enums in a map, they're lovin' it! } } public static Blah fromString(String s) { return STRING_TO_ENUM.get(s); // Maps lead straight to enums, no U-turns needed! Welcome to fast-track city. } }

In multi-threading environments, we need synchronization for multiple race cars. For that, ConcurrentHashMap is your track marshal.

Customize enums with strings and generics

Sometimes, we need specific strings associated with enum constants. For these advanced requirements, consider implementing private fields, constructors, and an associated getText() method:

public enum Blah { A("a"), B("b"), C("c"); private final String text; private Blah(String text) { this.text = text; // Yes, enums can also take an entrance exam. } public String getText() { return this.text; // Hey enum, can you tell us your text? Sure, here you go! } }

What if we want a generic solution to convert strings to enums across different enum types? Here you go:

public static <T extends Enum<T>> T fromString(Class<T> enumType, String name) { return Enum.valueOf(enumType, name.trim().toUpperCase()); // From a string, born an Enum! Generically yours. }

Handling exceptions

Enums are very particular about the strings they interact with, just like some food connoisseurs. Always handle their exceptions generously:

try { Day day = Day.valueOf("MONIY"); // Oops! A typo. } catch (IllegalArgumentException e) { // Handle the exception like the sophisticated coder you are. }