Switch String with Enum variables

Viewed 1172

I have got an Enum with different values and want to switch a string variable. Now I hit a wall trying to convert the Enum values to Strings, that I can use as case constant.

My best try was to convert the Enum to a String array, but the switch doesn't seem to accept array values as a case constant. (IntelliJ says: "constant expression required")

Enum myEnum = {FOO, BAR}

String input = "foo"

final String[] constant = Arrays.stream(myEnum.values()).map(Enum::name).toArray(String[]::new); 
//converts Enum to String[]; made it final, so it is "constant" 

       switch (input) {
                    case constant[0]:
                        System.out.println("foo");
                        break;
                    case constant[1]:
                        System.out.println("bar");
                        break;
                     }

Is there an elegant way to make this switch depend on the Enum?

4 Answers

You shouldn't convert it because it isn't needed. Also, your code won't even compile because case is a reserved keyword in Java.

You should take a look at the valueOf method of an Enum.

Your code can look like that:

public enum MyEnum {FOO, BAR}

//method
String input = "foo";
MyEnum niceFound = MyEnum.valueOf(input.toUpperCase());

That will return FOO but can throw an IllegalArgumentException when the given value isn't present as type.

You can do this :

public enum MyEnum {
    FOO("foo"),
    BAR("bar");

    private String value;

    public String getValue() {
        return value;
    }

    public static MyEnum getState(String value) {
        switch (value) {
            case "foo":
                return FOO;
            case "bar":
                return BAR;
        }
        return null;
    }

    private MyEnum(String value) {
        this.value = value;
    }
}

Now, in your class, you can :

MyEnum myEnum = getState("foo"); // returns MyEnum.FOO

Also make sure you handle the case when getState() returns null

Use MyEnum.valueOf(value.toUpperCase())

public enum MyEnum {
    FOO, BAR;
}

public static void process(String value) {
    try {
        switch (MyEnum.valueOf(value.toUpperCase())) {
            case FOO :
                System.out.println("FOO");
                break;
            case BAR :
                System.out.println("BAR");
                break;
            default :
                break;
        }
    }
    catch (IllegalArgumentException e) {
        // TODO: handle exception
    }

public static void main(String[] a){
    process("foo");
}

A solution with Java 8+ streams would be to create a method inside your enum :

public static Optional<MyEnum> getByValue(final String value) {
   return Arrays.stream(MyEnum.values())
              .filter(myEnum -> myEnum.value.equals(value))
              .findFirst();
}

This returns optional in case there is no enum value for your String parameter. But you can change it according to your needs.

Related