获取枚举值作为 Java 8 中的字符串列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29465943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:03:38  来源:igfitidea点击:

Get enum values as List of String in Java 8

javaenumsjava-8

提问by Suganthan Madhavan Pillai

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

是否有任何 Java 8 方法或简单方法,它将枚举值作为字符串列表返回,例如:

List<String> sEnum = getEnumValuesAsString();

采纳答案by Konstantin Yovkov

You can do (pre-Java 8):

您可以执行以下操作(Java 8 之前):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

或者

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

使用 Java 8 特性,您可以将每个常量映射到其名称:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

回答by Sandeep Patel

Enum :

枚举:

public enum UserCategory {

    EMPLOYEE_USER("Employee user"),
    CONTRACTOR_USER("Contractor User"),
    THIRD_PARTY_USER("Third-party User");

    private String desc;

    private UserCategory(String desc) {
        this.desc = desc;
    }
}

Getting Value As Array :

获取值作为数组:

  UserCategory.values());

Getting Value As List:

以列表形式获取价值:

  Arrays.asList(UserCategory.values());

回答by Raf

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 EnumUtilslibrary since the type of enum is not known at compile time.

为了验证,我不得不使用Apache's EnumUtils库,因为在编译时不知道枚举的类型。

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> 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

我懒得写一个枚举注释验证器,如下所示https://stackoverflow.com/a/51109419/1225551