gil.fernandes
gil.fernandes

Reputation: 14621

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

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?

Upvotes: 5

Views: 10448

Answers (2)

Michał Stochmal
Michał Stochmal

Reputation: 6630

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;.

Upvotes: 0

Andrew
Andrew

Reputation: 49646

Original post

Yes, that's a good Java 8 way, but...

The toString can be overridden, so you'd better go with Weather::name which returns the name of an enum constant (exactly as declared in the enum declaration) and can't be changed:

Stream.of(Weather.values()).map(Weather::name).toArray(String[]::new);

A bit of generics

I wrote a helper class to deal with any enum in a generic way:

class EnumUtils {

    public static <T extends Enum<T>> String[] getStringValues(Class<T> enumClass) {
        return getStringValuesWithStringExtractor(enumClass, Enum::name);
    }

    public static <T extends Enum<T>> String[] getStringValuesWithStringExtractor(
            Class<T> enumClass,
            Function<? super T, String> extractor
    ) {
        return of(enumClass.getEnumConstants()).map(extractor).toArray(String[]::new);
    }

}

Here is a demonstration:

enum Weather {
    RAINY, SUNNY, STORMY;

    @Override
    public String toString() {
        return String.valueOf(hashCode());
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(EnumUtils.getStringValues(Weather.class)));
        System.out.println(Arrays.toString(EnumUtils.getStringValuesWithStringExtractor(Weather.class, Weather::toString)));
    }

}

And the output:

[RAINY, SUNNY, STORMY]
[359023572, 305808283, 2111991224]

Upvotes: 12

Related Questions