What\'s the easiest and/or shortest way possible to get the names of enum elements as an array of String
s?
What I mean by this is that if, for example,
I did a bit test on @Bohemian's solution. The performance is better when using naive loop instead.
public static <T extends Enum<?>> String[] getEnumNames(Class<T> inEnumClass){
T [] values = inEnumClass.getEnumConstants();
int len = values.length;
String[] names = new String[len];
for(int i=0;i<values.length;i++){
names[i] = values[i].name();
}
return names;
}
//Bohemian's solution
public static String[] getNames(Class<? extends Enum<?>> e) {
return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}
I would write it like this
public static String[] names() {
java.util.LinkedList<String> list = new LinkedList<String>();
for (State s : State.values()) {
list.add(s.name());
}
return list.toArray(new String[list.size()]);
}
Another way to do it in Java 7 or earlier would be to use Guava:
public static String[] names() {
return FluentIterable.from(values()).transform(Enum::name).toArray(String.class);
}