1

I have enum:

public enum Enumz{
    FIRST_VALUE(0, "one"),
    SECOND_VALUE(1, "two"),
    THIRD_VALUE(2, "three")

    private int id;
    private String name;

}
    

How can I find enum value if my String value match with enum string name? For example: if I have String = "two" I need to get ENUMZ.SECOND_VALUE.

2
  • You could implement a get method within the enum, something like public Enumz getEnumzByName(String name). That method should do a comparison and return the Enumz for which the name equals the input name argument. Commented Aug 21, 2020 at 20:45
  • Your enum doesn't compile. There's a syntax error and a missing constructor. Commented Aug 22, 2020 at 12:45

2 Answers 2

3

You can use Java 8 stream alternative to for loop

String serachValue = "two";
Enumz enumz = Arrays.stream(Enumz.values())
                     .filter(v -> serachValue.equalsIgnoreCase(v.name))
                     .findFirst().orElse(null);

Good practice is always put it as a static method into the ENUM itself as explained by other @Sagar Gangwal.

Sign up to request clarification or add additional context in comments.

Comments

2
public enum Enumz {
    FIRST_VALUE(0, "one"),
    SECOND_VALUE(1, "two"),
    THIRD_VALUE(2, "three");

    private int id;
    private String name;

    Enumz(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static Enumz fromString(String text) {
        for (Enumz b : Enumz.values()) {
            if (b.name.equalsIgnoreCase(text)) {
                return b;
            }
        }
        return null;
    }

}
class Sample{
    public static void main(String[] args) {
        System.out.println(Enumz.fromString("two"));
    }
}

You can implement your own method inside enum and call that method every time you want enum using String.

Above code will printing an output as below

OUTPUT

SECOND_VALUE

1 Comment

I would modify the fromString() to EnumSet.allOf(Enumz.class).stream().filter(enumz -> name.equals(enumz.name)).findAny().orElse(null). That you use the EnumSet class and Stream.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.