如何从字符串中获取枚举值,如果值不匹配

huangapple go评论63阅读模式
英文:

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

问题

我有枚举:

public enum Enumz{
    FIRST_VALUE(0, "one"),
    SECOND_VALUE(1, "two"),
    THIRD_VALUE(2, "three")
    
    private int id;
    private String name;
}

如果我的字符串值与枚举字符串名称匹配,我该如何找到枚举值?例如:如果我有 String = "two",我需要获得 ENUMZ.SECOND_VALUE

英文:

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.

答案1

得分: 1

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"));
    }
}

OUTPUT

SECOND_VALUE

英文:
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

答案2

得分: 1

你可以使用Java 8的stream替代for循环

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

良好的做法是将它作为静态方法放入ENUM本身,正如其他人@Sagar Gangwal所解释的那样。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月22日 03:56:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63529338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定