Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all names in an enum as a String[]

Tags:

java

arrays

enums

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

like image 799
Konstantin Avatar asked Dec 09 '12 00:12

Konstantin


People also ask

How do I convert an enum to a string?

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.

How do I get a list of all enum values?

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.

How do I get a list of enum names?

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.

Can enum values be strings?

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.


1 Answers

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(", "); } 
like image 125
Bohemian Avatar answered Oct 07 '22 12:10

Bohemian