Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create List of enum from comma separated String in Java

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.

like image 400
Arpan Das Avatar asked Jun 29 '26 09:06

Arpan Das


2 Answers

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());
like image 95
Yassin Hajaj Avatar answered Jun 30 '26 23:06

Yassin Hajaj


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

Pattern.compile(regex)
       .splitAsStream(myString)
       .map(HttpStatus::valueOf)
       .collect(toList());
like image 21
Ousmane D. Avatar answered Jun 30 '26 23:06

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!