Did you know? Programmers convert coffee to code.

If you like my articles, sponsor me a coffee.

At the other end of the link I post some results of my other hobbies, like playing bass. It is worth checking it out ;)

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 -> e.name())
.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.

Share the knowledge!

Senior developer, consultant, author, mentor, apprentice. I love to share my knowledge and insights what I achieve through my daily work which is not trivial -- at least not for me.

Click Here to Leave a Comment Below

%d bloggers like this: