How to convert string array to enum array in java
arrays, enums, java
Solution
Here's a complete code example:
private static List<Season> foo(List<String> slist) {
List<Role> list = new ArrayList<>();
for (String val : slist) {
list.add(Season.valueOf(val));
}
return list;
}
Now if you want to make a generic method that would do this for any Enum, it gets a bit tricker. You have to use a "generic method":
private static <T extends Enum<T>> List<T> makeIt(Class<T> clazz, List<String> values) {
List<T> list = new ArrayList<>();
for (String level : values) {
list.add(Enum.valueOf(clazz, level));
}
return list;
}
You'd have to call this as follows:
List<Strings> slist = ....
List<Season> elist= makeIt(Season.class, slist);
Problem
I have a string array that contains the enum values taken from the user. How do I now convert this string array to enum array so that the elements can then be iterated and used further in other methods? This needs to be done in Java. Basically I am asking is that for example if I have this array ``` String [] names = {"Autumn", "Spring", "Autumn", "Autumn" }; ``` and I have this enum ``` enum Season { Autumn, Spring; } ``` How do I now convert the above array of String type to an array of enum Season type?