enum21
enum21

Reputation: 13

enum question. String and integer relationship

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?

Upvotes: 1

Views: 61

Answers (2)

Petr Aleksandrov
Petr Aleksandrov

Reputation: 1524

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.

Upvotes: 2

azro
azro

Reputation: 54168

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

Upvotes: 6

Related Questions