Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert a string to an enum and list its values

Short answer

valueOf() finds a constant by name, and name() returns the name back:

enum Status { NEW, PAID, SHIPPED }
 
void main() {
    Status status = Status.valueOf("PAID");
 
    IO.println(status);
    IO.println(status.name().toLowerCase());
}

Output:

PAID
paid

All values

values() returns an array of all constants in declaration order, and ordinal() the constant's number:

enum Status { NEW, PAID, SHIPPED }
 
void main() {
    for (Status s : Status.values()) {
        IO.println(s.ordinal() + " " + s);
    }
}

Output:

0 NEW
1 PAID
2 SHIPPED

Safe conversion

For user input, upper-case the string and handle an unknown value:

enum Status { NEW, PAID, SHIPPED }
 
Optional<Status> parse(String text) {
    try {
        return Optional.of(Status.valueOf(text.strip().toUpperCase(Locale.ROOT)));
    } catch (IllegalArgumentException e) {
        return Optional.empty();
    }
}
 
void main() {
    IO.println(parse(" paid "));
    IO.println(parse("lost"));
}

Output:

Optional[PAID]
Optional.empty

A custom field

Constants can hold data — for example, a label for the UI:

enum Size {
    S("Small"), M("Medium"), L("Large");
 
    private final String label;
 
    Size(String label) {
        this.label = label;
    }
 
    static Size fromLabel(String label) {
        return Arrays.stream(values()).filter(s -> s.label.equals(label)).findFirst().orElseThrow();
    }
}
 
void main() {
    IO.println(Size.fromLabel("Medium"));
}

Output:

M

Common mistake

valueOf() is case-sensitive and throws for an unknown name:

enum Status { NEW, PAID, SHIPPED }
 
void main() {
    Status.valueOf("paid");
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: No enum constant Main.Status.paid

Functions used in this recipe

  • enum — Declares an enum — a type with a fixed set of values.

Thanks for reading!

Donate to the site — we work hard for you.