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 had the following enum:
public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; public static String[] names() { // ... } }
the names()
method would return the array { "NEW", "RUNNABLE", "BLOCKED", "WAITING", "TIMED_WAITING", "TERMINATED" }
.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
Use a list comprehension to get a list of all enum values, e.g. values = [member. value for member in Sizes] . On each iteration, access the value attribute on the enum member to get a list of all of the enum's values.
However, enum values are required to be valid identifiers, and we're encouraged to use SCREAMING_SNAKE_CASE by convention. Given those limitations, the enum value alone is not suitable for human-readable strings or non-string values.
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(", "); }
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