How to get an enum value from a String in Java?

July 15, 2020 No comments Java enum String QA solved

1. Introduction

An enum is a special class in Java that represents a group of constants. In this short tutorial, we are going to present how to get enum value using String.

2. The problem: Get enum using String value

Let's say we have the following enum Alphabet:

public enum Alphabet {
    A,
    B,
    C,
    D,
    E,
    F,
    G
}

We want to find the enum value of a String, for example, "A" which would be Alphabet.A.

3. Solution1: Use Enum.valueOf(...) method

Use Alphabet.valueOf(str) method.

This method returns the enum with the specified name. The name must match exactly an identifier. For example to get Alphabet.A we need to use Alphabet.valueOf("A").

Note that if the specified enum type has no constant with the specified name the IllegalArgumentException will the thrown.

This could happen for:

  • Alphabet.valueOf("A ") - note space at the end,
  • Alphabet.valueOf("9") - no such contant in Alphaget enum,
  • Alphabet.valueOf("a") - method is case sensitive.

4. Solution2: Filtering enum values

You can also manually filter enum values from specified type like in the following example:

import java.util.Arrays;

public enum Alphabet {
    A,
    B,
    C,
    D,
    E,
    F,
    G;

    public static Alphabet findCaseInsensitive(String str) {
        return Arrays.stream(Alphabet.values())
                     .filter(alphabet -> str.equalsIgnoreCase(alphabet.name()))
                     .findFirst()
                     .orElseThrow(() -> new IllegalArgumentException("No constant found"));
    }
}

In this example we used String.equalsIgnoreCase(...) to compare specified String with enum values in case-insensitive way.

Now to find Alphabet.A we can use this method like in the following snippet:

Alphabet al = Alphabet.findCaseInsensitive("a");

The al variable will be equal to Alphabet.A

5. Solution3: Checking enum values without throwing an exception

To check if enum contains constant A without throwing an exception we can use Guava library.

In the following code we used Enums utility class from Guava:

Optional<Alphabet> opt = Enums.getIfPresent(Alphabet.class, "A")

The getIfPresent(...) method will return Optional.empty() if Alphabet doesn't have A value.

You can also implement this method on your own in Plain Java:

import java.util.Arrays;

public enum Alphabet {
    A,
    B,
    C,
    D,
    E,
    F,
    G;

    public static Optional<Alphabet> getIfPresent(String str) {
        return Arrays.stream(Alphabet.values())
                     .filter(alphabet -> str.equals(alphabet.name()))
                     .findFirst();
    }
}
{{ message }}

{{ 'Comments are closed.' | trans }}