[java] Getting all names in an enum as a String[]

What's the easiest and/or shortest way possible to get the names of enum elements as an array of Strings?

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" }.

This question is related to java arrays enums

The answer is


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);

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;
}

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.


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);
}

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.


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(",");
    }
}

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.


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);
}

With java 8:

Arrays.stream(MyEnum.values()).map(Enum::name)
                    .collect(Collectors.toList()).toArray();

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()]);
}

the ordinary way (pun intended):

String[] myStringArray=new String[EMyEnum.values().length];
for(EMyEnum e:EMyEnum.values())myStringArray[e.ordinal()]=e.toString();

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


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);
}

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()


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));
    }
}

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()));

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);

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.


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;
}

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);
}

Got the simple solution

Arrays.stream(State.values()).map(Enum::name).collect(Collectors.toList())

org.apache.commons.lang3.EnumUtils.getEnumMap(State.class).keySet()


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(", ");
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to enums

Enums in Javascript with ES6 Check if value exists in enum in TypeScript Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? TypeScript enum to object array How can I loop through enum values for display in radio buttons? How to get all values from python enum class? Get enum values as List of String in Java 8 enum to string in modern C++11 / C++14 / C++17 and future C++20 Implementing Singleton with an Enum (in Java) Swift: Convert enum value to String?