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

时间:2017-08-04 12:44:41

标签: java arrays

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 个答案:

答案 0 :(得分:9)

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]

答案 1 :(得分:0)

如果您经常将枚举值转换为任何类型的数组,则可以将其值预先计算为静态字段:

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

并像Weather.STRINGS;一样使用它。