Get enum values as List of String in Java 8

前端 未结 2 549
南方客
南方客 2020-12-08 01:49

Is there any Java 8 method or easy way, which returns Enum values as a List of String, like:

List sEnum = getEnumValuesAsString();
2条回答
  •  孤城傲影
    2020-12-08 02:10

    You could also do something as follow

    public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
    EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
    

    or

    EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
    

    The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

    For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void isValidEnumsValid(Class clazz, Set enumNames) {
        Set notAllowedNames = enumNames.stream()
                .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
                .collect(Collectors.toSet());
    
        if (notAllowedNames.size() > 0) {
            String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
                .collect(Collectors.joining(", "));
    
            throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                    .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                    + "of the following : " + validEnumNames);
        }
    }
    

    I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

提交回复
热议问题