Reputation: 313
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
.
Upvotes: 0
Views: 741
Reputation: 2701
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
Upvotes: 5
Reputation: 1
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());
👍 😀
Upvotes: 0