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,
Here's one-liner for any enum
class:
public static String[] getNames(Class<? extends Enum<?>> e) {
return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}
Pre Java 8 is still a one-liner, albeit less elegant:
public static String[] getNames(Class<? extends Enum<?>> e) {
return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
}
That you would call like this:
String[] names = getNames(State.class); // any other enum class will work
If you just want something simple for a hard-coded enum class:
public static String[] names() {
return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");
}
With java 8:
Arrays.stream(MyEnum.values()).map(Enum::name)
.collect(Collectors.toList()).toArray();
Something like this would do:
public static String[] names() {
String[] names = new String[values().length];
int index = 0;
for (State state : values()) {
names[index++] = state.name();
}
return names;
}
The documentation recommends using toString() instead of name() in most cases, but you have explicitly asked for the name here.
I have the same need and use a generic method (inside an ArrayUtils class):
public static <T> String[] toStringArray(T[] array) {
String[] result=new String[array.length];
for(int i=0; i<array.length; i++){
result[i]=array[i].toString();
}
return result;
}
And just define a STATIC inside the enum...
public static final String[] NAMES = ArrayUtils.toStringArray(values());
Java enums really miss a names() and get(index) methods, they are really helpful.
i'd do it this way (but i'd probably make names an unmodifiable set instead of an array):
import java.util.Arrays;
enum State {
NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED;
public static final String[] names=new String[values().length];
static {
State[] values=values();
for(int i=0;i<values.length;i++)
names[i]=values[i].name();
}
}
public class So13783295 {
public static void main(String[] args) {
System.out.println(Arrays.asList(State.names));
}
}
If you want the shortest you can try
public static String[] names() {
String test = Arrays.toString(values());
return text.substring(1, text.length()-1).split(", ");
}