简体   繁体   中英

How to convert list of enums into array of strings?

I've had an array of enums like below:

enum CountryEnum {
   MADAGASCAR,
   LESOTHO,
   BAHAMAS,
   TURKEY,
   UAE
}

List<CountryEnum> countryList = new ArrayList<>();
countryList.add(CountryEnum.MADAGASCAR);
countryList.add(CountryEnum.BAHAMAS);

How to convert my countryList into String[] ?

I try eq in this way:

String[] countries = countryList.toArray(String::new);

but it return me ArrayStoreException .

Thanks for any help!

Thanks for any help!

It should work so:

 String[] strings = countryList.stream()
                    .map(Enum::toString)
                    .toArray(String[]::new);

Try this:

CountryEnum[] arr = countryList.stream().toArray(CountryEnum[] ::new);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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