2

I have an Enum class, where each Enum has a String value.

I want to create a List<> with my Enum type from a 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";
    }

}

P.S. I need to directly assign the String-list to MyEnum-list as above. I cannot do a loop on the String-list and add one by one.

2
  • What content-type are you getting and how are you converting it? Commented Feb 18, 2019 at 14:32
  • What is the expected result? Commented Feb 18, 2019 at 14:34

3 Answers 3

1

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
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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Will only work if strings contain the names of the enums
0

In case you use Java 8 and if stringList contains the names of the enums;

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

1 Comment

Will only work if stringList contains the names of the enums

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.