简体   繁体   English

Java:如何将字符串 ArrayList 分配给列表<Enum>

[英]Java: How to assign an String ArrayList to an List<Enum>

I have an Enum class, where each Enum has a String value.我有一个 Enum 类,其中每个 Enum 都有一个 String 值。

I want to create a List<> with my Enum type from a List.我想从列表中使用我的 Enum 类型创建一个 List<>。 Here the strings are the value of the enums.这里的字符串是枚举的值。

Is it possible to assign them directly during initialization?是否可以在初始化期间直接分配它们? If yes, what is the best way to do that?如果是,那么最好的方法是什么?

here is an example code:这是一个示例代码:

public class SomeController {

    public enum MyEnum {
        A("a"),
        B("b"),
        C("c");

        private final String value;

        MyEnum(String value) {
            this.value = value;
        }
    }

    public String handler(
            @RequestParam(name = "enumList") List<MyEnum> myEnumList ) {

        //do something with myEnumList

        return "something";
    }

}

PS I need to directly assign the String-list to MyEnum-list as above. PS我需要直接将String-list分配给MyEnum-list,如上所述。 I cannot do a loop on the String-list and add one by one.我无法对字符串列表进行循环并一一添加。

First create a map of all the enum constants inside your enum:首先创建枚举中所有枚举常量的映射:

private static final Map<String, MyEnum> CONSTANTS = Arrays.stream(values())
    .collect(Collectors.toMap(e -> e.value, e -> e));

And then create a lookup method with @JsonCreator in your enum:然后在枚举中使用@JsonCreator创建一个查找方法:

@JsonCreator
public static MyEnum fromValue(String value) {
   MyEnum myEnum = CONSTANTS.get(value);
   if(myEnum == null) {
       throw new NoSuchElementException(value);
   }
   return myEnum;
}

Jackson will detect the json creator method and uses it to convert your list of strings into a list of enums (It all does this before even entering your handler method) Jackson 将检测 json creator 方法并使用它来将您的字符串列表转换为枚举列表(这一切都在进入您的handler方法之前完成)

In case you use Java 8 and if stringList contains the names of the enums;如果您使用 Java 8 并且 stringList 包含枚举的名称;

List<MyEnum> myenums = stringList
        .stream()
        .map(MyEnum::valueOf)
        .collect(Collectors.toList());

You can do something like this:你可以这样做:

public static <T extends Enum<T>> List<T> toEnumList(
        Iterable<String> strings, Class<T> clazz) {
    List<T> result = new ArrayList<>();
    for (String s : strings) {
        result.add(Enum.valueOf(clazz, s));
    }
    return result;
}

It works with any enum type.它适用于任何枚举类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM