1. Introduction

In this quick tutorial, we'll examine different ways of converting a String to an enum constant in Java.

To be more precise, we'll retrieve an enum constant via its String property.

2. Sample Enum

Let's first look at our sample enum:

public enum Direction {
    NORTH("north"),
    SOUTH("south"),
    WEST("west"),
    EAST("east");

    private final String name;

    Direction(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

The Direction enum contains one String property, name. It also defines four constants.

3. Built-in Support

By default, every enum class includes the static valueOf method. When given an enum constant name, valueOf returns the matched enum constant:

@Test
public void shouldConvertFromEnumConstant() {
    final Direction direction = Direction.valueOf("NORTH");
    assertEquals(Direction.NORTH, direction);
}

Here, Direction.NORTH is retrieved from the String value NORTH.

However, when we want to retrieve Direction from its name property - not from its constant name - the built-in methods don't help us. This means that we must write our own creator method that will take a String value and match it with one of the Direction constants.

4. Iteration

Firstly, we'll create a static method that iterates over all constant values. In each iteration, it'll compare the given value with the name property:

public static Direction fromValue(String givenName) {
    for (Direction direction : values()) {
        if (direction.name.equals(givenName)) {
            return direction;
        }
    }
    return null;
}

Note that we'll perform this iteration in each invocation.

5. Stream

We'll now perform a similar iteration with Stream operators:

public static Direction fromValue(String givenName) {
    return Stream.of(values())
                 .filter(direction -> direction.name.equals(givenName))
                 .findFirst()
                 .orElse(null);
}

This method produces the same result as the previous one.

6. Map

So far we've iterated over the constant values and performed it for each method invocation. Iteration gives us more options during the comparison. For example, we can compare the name property and the given value ignoring the case. However, if we need only the exact matches, we can instead use a Map.

We must first construct a Map from the constant values:

private static Map<String, Direction> nameToValue;
static {
    nameToValue = Stream.of(values()).collect(Collectors.toMap(Direction::getName, Function.identity()));
}

Then we can implement our creator method:

public static Direction fromValueVersion3(String givenName) {
    return nameToValue.get(givenName);
}

7. Summary

In this tutorial, we've looked at how we can convert a String to an enum constant.

Finally, check out the source code for all examples over on Github.