简体   繁体   English

枚举问题。 字符串与integer的关系

[英]enum question. String and integer relationship

I have a basic if-else if block of code.我有一个基本的 if-else if 代码块。 Here is the simplified version这是简化版

if (var == 1) {
  finalString = "string1";
} else if (var == 3) {
  finalString = "string3";
} else if (var == 4) {
  finalString = "string4";
} else {
  finalString = "no string found";
}

I am trying to use enums approach, so I created an enum class我正在尝试使用枚举方法,所以我创建了一个枚举 class

public enum MyValues {
  string1(1),
  string2(3),
  string4(4);
  ...
  ...
}

Is there a way to improve my if/else statements with the enum I created?有没有办法用我创建的枚举来改进我的 if/else 语句?

If you really HAVE TO use enums, you can do something like this:如果你真的必须使用枚举,你可以这样做:

    public enum MyValues {
        string1(1),
        string2(3),
        string4(4),
        default_value(-1);

        private final int key;
        MyValues(int key) {
            this.key = key;
        }

        public MyValues getByKey(int key){
            return Arrays.stream(values())
                    .filter(e -> e.key == key)
                    .findAny()
                    .orElse(default_value);
        }
    }

If you don't have to use enums, then see azro's answer .如果您不必使用枚举,请参阅azro 的答案

You'd better use a Map for mapping int <--> String你最好使用Map来映射int <--> String

Map<Integer, String> map = Map.of(1, "string1", 2, "string2", 3, "string3");

int aKey = 1;
String finalString = map.getOrDefault(aKey, "no string found");

System.out.println(map.getOrDefault( 1, "no string found"));  // string1
System.out.println(map.getOrDefault(10, "no string found"));  // no string found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM