BokuNoHeeeero
BokuNoHeeeero

Reputation: 313

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

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

but it returned me ArrayStoreException.

Upvotes: 0

Views: 741

Answers (2)

Georgii Lvov
Georgii Lvov

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

Dechire T
Dechire T

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

Related Questions