More on Java Enumerations

In the previous article I have written about Java enumerations. Now I will add some extension to it where I introduce a generic approach usable on enums.

Now I encountered an issue with our UI multiple select filter. There you have to provide the available values as a String[] — and they can be filled with enum names or other values of enums.

One of the developers added a toStringArray method to every enum used for such filter elements. Well, this was not the most beautiful solution — and the draw-back was that you have to implement this method for every enum you want to use for such a purpose.

By the way this code snippet he found as the first result in Google for the query: “java enum names to string array”.  If you look at the solution you can see that it uses an old-fashioned for loop and the co-worker copied the whole code.

Well, I thought there should exist a way where I can write this functionality more generic. And of course there is one.

That’s why I have written a simple utility class to contain such methods. And my solution for Java 8 is the following:

public static <E extends Enum<E>> String[] getEnumNames(final Class<E> enumClass) {
    return Stream.of(enumClass.getEnumConstants()).filter(e -> e != null).map(e ->
.toArray(size -> new String[size]);

It utilizes the functionality of the Stream API introduced with Java 8.The null-check is optional because enum values are not null but I like to add this type of check as a good (or bad?) practice to my code.

This solution can be migrated back to Java 7 too. In this case it would look like this:

public static <E extends Enum<E>> String[] getEnumNames(final Class<E> enumClass) {
    List<String> names = new ArrayList<>();
    for(E e : enumClass.getEnumConstants()) {
    return names.toArray(new String[] {});

As you can see, the solution is very simple and can be used widely.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s