1

I have a basic if-else if block of code. 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

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

Is there a way to improve my if/else statements with the enum I created?

0

2 Answers 2

6

You'd better use a Map for mapping 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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.