Getting all names in an enum as a String[]
JavaArraysEnumsJava Problem Overview
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" }
.
Java Solutions
Solution 1 - Java
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(", ");
}
Solution 2 - Java
Create a String[]
array for the names and call the static values()
method which returns all the enum values, then iterate over the values and populate the names array.
public static String[] names() {
State[] states = values();
String[] names = new String[states.length];
for (int i = 0; i < states.length; i++) {
names[i] = states[i].name();
}
return names;
}
Solution 3 - Java
Here`s an elegant solution using Apache Commons Lang 3:
EnumUtils.getEnumList(State.class)
Although it returns a List, you can convert the list easily with list.toArray()
Solution 4 - Java
If you can use Java 8, this works nicely (alternative to Yura's suggestion, more efficient):
public static String[] names() {
return Stream.of(State.values()).map(State::name).toArray(String[]::new);
}
Solution 5 - Java
With java 8:
Arrays.stream(MyEnum.values()).map(Enum::name)
.collect(Collectors.toList()).toArray();
Solution 6 - Java
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()]);
}
Solution 7 - Java
Another ways :
First one
Arrays.asList(FieldType.values())
.stream()
.map(f -> f.toString())
.toArray(String[]::new);
Other way
Stream.of(FieldType.values()).map(f -> f.toString()).toArray(String[]::new);
Solution 8 - Java
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.
Solution 9 - Java
Got the simple solution
Arrays.stream(State.values()).map(Enum::name).collect(Collectors.toList())
Solution 10 - Java
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));
}
}
Solution 11 - Java
My solution, with manipulation of strings (not the fastest, but is compact):
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
public static String[] names() {
String valuesStr = Arrays.toString(State.values());
return valuesStr.substring(1, valuesStr.length()-1).replace(" ", "").split(",");
}
}
Solution 12 - Java
the ordinary way (pun intended):
String[] myStringArray=new String[EMyEnum.values().length];
for(EMyEnum e:EMyEnum.values())myStringArray[e.ordinal()]=e.toString();
Solution 13 - Java
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.
Solution 14 - Java
org.apache.commons.lang3.EnumUtils.getEnumMap(State.class).keySet()
Solution 15 - Java
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);
}
Solution 16 - Java
Very similar to the accepted answer, but since I learnt about EnumSet, I can't help but use it everywhere. So for a tiny bit more succinct (Java8) answer:
public static String[] getNames(Class<? extends Enum<?>> e) {
return EnumSet.allOf(e).stream().map(Enum::name).toArray(String[]::new);
}
Solution 17 - Java
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(", ");
}
Solution 18 - Java
Just a thought: maybe you don't need to create a method to return the values of the enum as an array of strings.
Why do you need the array of strings? Maybe you only need to convert the values when you use them, if you ever need to do that.
Examples:
for (State value:values()) {
System.out.println(value); // Just print it.
}
for (State value:values()) {
String x = value.toString(); // Just iterate and do something with x.
}
// If you just need to print the values:
System.out.println(Arrays.toString(State.values()));
Solution 19 - Java
Try this:
public static String[] vratAtributy() {
String[] atributy = new String[values().length];
for(int index = 0; index < atributy.length; index++) {
atributy[index] = values()[index].toString();
}
return atributy;
}
Solution 20 - Java
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);
}
Solution 21 - Java
You can put enum values to list of strings and convert to array:
List<String> stateList = new ArrayList<>();
for (State state: State.values()) {
stateList.add(state.toString());
}
String[] stateArray = new String[stateList.size()];
stateArray = stateList.toArray(stateArray);
Solution 22 - Java
The easiest way:
Category[] category = Category.values();
for (int i = 0; i < cat.length; i++) {
System.out.println(i + " - " + category[i]);
}
Where Category is Enum
name
Solution 23 - Java
You can get Enum String value by "Enum::name"
public static String[] names() {
return Arrays.stream(State.values()).map(Enum::name).toArray(String[]::new);
}
This implementation does not require additional "function" and "field". Just add this function to get the result you want.
Solution 24 - Java
Basing off from Bohemian's answer for Kotlin:
Use replace()
instead of replaceAll()
.
Arrays.toString(MyEnum.values()).replace(Regex("^.|.$"), "").split(", ").toTypedArray()
Side note: Convert to .toTypedArray()
for use in AlertDialog
's setSingleChoiceItems
, for example.
Solution 25 - Java
enum CardType {
CLUB, DIAMOND, HEART, SPADE;
}
public class Control {
public static void main(String[] args) {
String[] cardsArray = new String[CardType.values().length];
int i = 0;
for (CardType cardType : CardType.values()){
cardsArray[i] = cardType.name();
i++;
}
//to output the array
for (int j = 0; j < CardType.values().length; j++){
System.out.println(cardsArray[j]);
}
}
}
Solution 26 - Java
You don't need to use the Streams API or the Apache Commons library. Here is arguably the simplest and the fastest way to do this:
public static String[] names() {
String[] names = new String[State.values().length];
State[] values = State.values();
for (int i = 0, valuesLength = values.length; i < valuesLength; i++) {
names[i] = values[i].toString();
}
return names;
}