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.

1
  • 1
    did you really get that error? or is the posted code wrong, missing the second [] like in String[] countries = countryList.toArray(String[]::new); Commented Jan 31, 2022 at 9:29

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

the answer is correct, but it could benefit from some clarification as to why it is done this way
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());

👍 😀

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.