Taras
Taras

Reputation: 469

How to get enum value from string if value doesn't match

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.

Upvotes: 1

Views: 1561

Answers (2)

Sujitmohanty30
Sujitmohanty30

Reputation: 3316

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.

Upvotes: 3

Sagar Gangwal
Sagar Gangwal

Reputation: 7937

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

Upvotes: 2

Related Questions