如何将枚举列表转换为字符串数组?

Bok*_*ero 0 java

我有一个枚举数组,如下所示:

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

List<CountryEnum> countryList = new ArrayList<>();
countryList.add(CountryEnum.MADAGASCAR);
countryList.add(CountryEnum.BAHAMAS);
Run Code Online (Sandbox Code Playgroud)

如何将我的转换countryListString[]

我试过这样:

String[] countries = countryList.toArray(String::new);
Run Code Online (Sandbox Code Playgroud)

但它又回到了我ArrayStoreException

Geo*_*vov 5

它应该这样工作:

 String[] strings = countryList.stream() // create Stream of enums from your list
                    .map(Enum::toString) // map each enum to desired string (here we take simple toString() for each enum)
                    .toArray(String[]::new); // collect it into string array
Run Code Online (Sandbox Code Playgroud)