Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string result of enum with overridden toString() back to enum?

Tags:

Given the following java enum:

public enum AgeRange {     A18TO23 {         public String toString() {                     return "18 - 23";         }     },    A24TO29 {         public String toString() {                     return "24 - 29";         }     },    A30TO35 {         public String toString() {                     return "30 - 35";         }     },  } 

Is there any way to convert a string value of "18 - 23" to the corresponding enum value i.e. AgeRange.A18TO23 ?

Thanks!

like image 670
Kevin Avatar asked Oct 27 '08 14:10

Kevin


2 Answers

The best and simplest way to do it is like this:

public enum AgeRange {     A18TO23 ("18-23"),     A24TO29 ("24-29"),     A30TO35("30-35");      private String value;      AgeRange(String value){         this.value = value;     }      public String toString(){         return value;     }      public static AgeRange getByValue(String value){         for (final AgeRange element : EnumSet.allOf(AgeRange.class)) {             if (element.toString().equals(value)) {                 return element;             }         }         return null;     } } 

Then you just need to invoke the getByValue() method with the String input in it.

like image 77
sakana Avatar answered Oct 11 '22 05:10

sakana


You could always create a map from string to value - do so statically so you only need to map it once, assuming that the returned string remains the same over time. There's nothing built-in as far as I'm aware.

like image 26
Jon Skeet Avatar answered Oct 11 '22 03:10

Jon Skeet