Most convenient way to convert enumeration values to string array in Java

Viewed 7988

This is about converting the enumeration values to a string array. I have an enumeration:

enum Weather {
    RAINY, SUNNY, STORMY
}

And I want to convert this to a string array with minimal effort and no loops with Java 8+. This is the best I came up with:

Arrays.stream(Weather.values()).map(Enum::toString).toArray(String[]::new)

Any other and similarly or more convenient ways to do the same thing?

2 Answers

If you're frequently converting enum values to any kind of array you can as well precompute it values as static field:

enum Weather {
    RAINY, SUNNY, STORMY;
    
    public static final String[] STRINGS = Arrays.stream(Weather.values())
                                                 .map(Enum::name)
                                                 .collect(Collectors.toList())
                                                 .toArray(new String[0]);
}

And use it just like that Weather.STRINGS;.

Related