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

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

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

问题

我有枚举:

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

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

英文:

I have enum:

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

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

  1. public enum Enumz {
  2. FIRST_VALUE(0, "one"),
  3. SECOND_VALUE(1, "two"),
  4. THIRD_VALUE(2, "three");
  5. private int id;
  6. private String name;
  7. Enumz(int id, String name) {
  8. this.id = id;
  9. this.name = name;
  10. }
  11. public static Enumz fromString(String text) {
  12. for (Enumz b : Enumz.values()) {
  13. if (b.name.equalsIgnoreCase(text)) {
  14. return b;
  15. }
  16. }
  17. return null;
  18. }
  19. }
  20. class Sample {
  21. public static void main(String[] args) {
  22. System.out.println(Enumz.fromString("two"));
  23. }
  24. }

OUTPUT

SECOND_VALUE

英文:
  1. public enum Enumz {
  2. FIRST_VALUE(0, "one"),
  3. SECOND_VALUE(1, "two"),
  4. THIRD_VALUE(2, "three");
  5. private int id;
  6. private String name;
  7. Enumz(int id, String name) {
  8. this.id = id;
  9. this.name = name;
  10. }
  11. public static Enumz fromString(String text) {
  12. for (Enumz b : Enumz.values()) {
  13. if (b.name.equalsIgnoreCase(text)) {
  14. return b;
  15. }
  16. }
  17. return null;
  18. }
  19. }
  20. class Sample{
  21. public static void main(String[] args) {
  22. System.out.println(Enumz.fromString("two"));
  23. }
  24. }

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循环

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

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

英文:

You can use Java 8 stream alternative to for loop

  1. String serachValue = "two";
  2. Enumz enumz = Arrays.stream(Enumz.values())
  3. .filter(v -> serachValue.equalsIgnoreCase(v.name))
  4. .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:

确定