0

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've tried this way:

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

but it returned me ArrayStoreException.

eis
  • 51,991
  • 13
  • 150
  • 199
BokuNoHeeeero
  • 243
  • 1
  • 2
  • 11
  • 1
    did you really get that error? or is the posted code wrong, missing the second `[]` like in `String[] countries = countryList.toArray(String[]::new);` – user16320675 Jan 31 '22 at 09:29

2 Answers2

5

It should work so:

 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
Georgii Lvov
  • 1,771
  • 1
  • 3
  • 17
  • the answer is correct, but it could benefit from some clarification as to why it is done this way – eis Jan 31 '22 at 09:27
0

you can try this:

enum CountryEnum {
   MADAGASCAR("Madagascar"),
   LESOTHO("Lesotho"),
   BAHAMAS("Bahamas"),
   TURKEY("Turkey"),
   UAE("UAE");

    String country;
    CountryEnum(String country) {
        this.country = country;
    }
    
    public String getCountry() {
        return country;
    }
}

I added a constructor to be able to get (in String) enum's values. Now you can just use:

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