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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With