Skip to content

Instantly share code, notes, and snippets.

@shui
Created May 25, 2018 08:12
Show Gist options
  • Save shui/63e6d854461a50c1aa2b0cdf83144625 to your computer and use it in GitHub Desktop.
Save shui/63e6d854461a50c1aa2b0cdf83144625 to your computer and use it in GitHub Desktop.
两个使用Enum查找字符串的实现

https://stackoverflow.com/questions/604424/lookup-java-enum-by-string-value

public enum Blah
{
    A("text1"),
    B("text2"),
    C("text3"),
    D("text4");

    private String text;

    Blah(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

    public static Blah fromText(String text) {
        return Arrays.stream(values())
          .filter(bl -> bl.text.equalsIgnoreCase(text))
          .findFirst()
          .orElse(null);
    }
}
public enum MyEnum {
    VALUE_1("Super"),
    VALUE_2("Rainbow"),
    VALUE_3("Dash"),
    VALUE_3("Rocks");

    private final String value;

    MyEnum(String value) {
        this.value = value;
    }

    /**
     * @return the Enum representation for the given string.
     * @throws IllegalArgumentException if unknown string.
     */
    public static MyEnum fromString(String s) throws IllegalArgumentException {
        return Arrays.stream(MyEnum.values())
                .filter(v -> v.value.equals(s))
                .findFirst();
                .orElseThrow(() -> new IllegalArgumentException("unknown value: " + s));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment