1

I am new to java and now I am trying to see if its possible to get ENUM from the string value it is assigned.

Consider for example i have this below ENUM ( i have corrected to give complete structure)

public enum Signal{
    RED("stop"), GREEN("start"), ORANGE("slow down");

    private String value;

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

    public String getValue() {
        return value;
    }
}

Is it possible to determine ENUM if i have the value which is assigned to it. That is is possible to get RED if i have "stop"

When i searched in internet the "valueof" is discussed which is not what i need as it helps the different purpose. Any reference would be greatly appreciated as well. Thank you for reading!!

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
linux developer
  • 821
  • 1
  • 13
  • 34
  • 3
    You'll have to write your own method. – Sotirios Delimanolis Mar 03 '14 at 19:03
  • See the second answer [here](http://stackoverflow.com/questions/604424/java-convert-string-to-enum). – Sotirios Delimanolis Mar 03 '14 at 19:04
  • 1
    Your enum definition is invalid; your values all use a constructor that you have not defined. – ruakh Mar 03 '14 at 19:05
  • I dint give the full ENUm structure i tried. Inlcuded the full definition above. Is this still in-correct with the way i have defined my enum? – linux developer Mar 03 '14 at 19:08
  • The general pattern for this is to have a static `Map` - in your case Map - which you initialize in a static block inside the enum class. In that map you put each enum value with with as key the the value you pass to the constructor - or simply call getValue() - . Then finally have a static method for retrieving your values, for example: `Signal getByValue(String)` – A4L Mar 03 '14 at 19:18

1 Answers1

3
public enum Signal{
  ...

  public static Signal byValue(String value) {
    Singal[] signales = Signal.getEnumConstants();
    for (Signal s:signals) {
       if (s.getValue().equals(value) {
         return s;
       }
    }
  }
}
Rene M.
  • 2,660
  • 15
  • 24