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:

</p>
<p>public static &amp;amp;lt;E extends Enum&amp;amp;lt;E&amp;amp;gt;&amp;amp;gt; String[] getEnumNames(final Class&amp;amp;lt;E&amp;amp;gt; enumClass) {<br />
    return Stream.of(enumClass.getEnumConstants()).filter(e -&amp;amp;gt; e != null).map(e -&amp;amp;gt; e.name())<br />
.toArray(size -&amp;amp;gt; new String[size]);<br />
}<br />

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:

<br />
public static &amp;amp;lt;E extends Enum&amp;amp;lt;E&amp;amp;gt;&amp;amp;gt; String[] getEnumNames(final Class&amp;amp;lt;E&amp;amp;gt; enumClass) {<br />
    List&amp;amp;lt;String&amp;amp;gt; names = new ArrayList&amp;amp;lt;&amp;amp;gt;();<br />
    for(E e : enumClass.getEnumConstants()) {<br />
        names.add(e.name());<br />
    }<br />
    return names.toArray(new String[] {});<br />
}<br />

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

Share the knowledge!
GHajba

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: