2

I need to create a List of enum from a comma separated String. I have some configurations in properties file which are mainly a list of HttpStatus

like:

some.config=TOO_MANY_REQUESTS,GATEWAY_TIMEOUT,BAD_GATEWAY 

This configurations can be bind to a LIST as:

@Value("#{'${some.config}'.split(',')}")
private List<HttpStatus> statuses;

Now can this be done with a single line of my code. I am receiving the String as following:

 @Bean(name = "somebean")
 public void do(@Value("${some.config:}") String statuses) throws IOException {

        private List<HttpStatus>  sList = StringUtils.isEmpty(statuses) ? 
        globalSeries : **Arrays.asList(statuses.split("\\s*,\\s*"));**

 }

Arrays.asList(series.split("\s*,\s*")); will create a List of string, now can I create a List of enum instead, otherwise I need to iterate the temp List then create a List of enum.

Arpan Das
  • 1,015
  • 3
  • 24
  • 57
  • 2
    How about something like `List list = Stream.of(yourData.split(delimiter).map(YourEnum::valueOf).collect(Collectors.toList())`? Anyway possibly related: [Lookup Java enum by string value](https://stackoverflow.com/q/604424) – Pshemo Jun 08 '18 at 09:23
  • @Pshemo I though the same, just somehow handle invalid input by catching `IllegalArgumentException` somewhere – Glains Jun 08 '18 at 09:25
  • 2
    Are you sure you want a `List` (allow duplicates, maintain an order)? For most practical use cases, you want a `Set`, likely an `EnumSet`. `Arrays.stream(statuses.split(",")) .map(s -> HttpStatus.valueOf(s.trim())) .collect(Collectors.toCollection( () -> EnumSet.noneOf(HttpStatus.class) ))` – Holger Jun 08 '18 at 10:03

2 Answers2

8

You could just use a stream and map all the String values into the Enum values using Enum#valueOf

Arrays.stream(statuses.split("\\s*,\\s*"))
      .map(HttpStatus::valueOf)
      .collect(Collectors.toList());
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
5

You can also use a Pattern to accomplish the task at hand:

Pattern.compile(regex)
       .splitAsStream(myString)
       .map(HttpStatus::valueOf)
       .collect(toList());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126