2

Let's say I have an enum as such:

public enum Fruit {
    APPLES("Apples"),
    BANANAS("Bananas"),
    PEAR("Pear"),
    ORANGE("Oranges");

    private final String string;

    Fruit(String string) {
        this.string = string;
    }
}

What would be the best way to generate a String[] array containing the string values of the enum, i.e. "Apples", "Bananas, "Pear", "Oranges"

I can think of a few ways but they could get messy and I'm wondering if there is a direct way to get these values.

2 Answers 2

8

Here's the shortest one I could come up with:

Arrays.stream(Fruit.values()).map(Fruit::getName).toArray(String[]::new);

Fruit.getName() would be a method returning the string field in the Enum

Sign up to request clarification or add additional context in comments.

3 Comments

Upvote because of using Java8 syntax. This is the only up-to-date solution.
I'd says that Arrays.stream(Fruit.values()) would be better than EnumSet.allOf(Fruit.class).stream(), being shorter and not requiring the creation of an EnumSet.
Good point, my mind instantly went for an EnumSet (as that's what I most commonly use) without thinking over other options. I have edited the answer.
2

You may do something like this.

Arrays.toString(Fruit.values()).replaceAll("^.|.$", "").split(", ");

2 Comments

In my case there may be certain enum constants whose "name" string does not match the enum constant's name. So I wouldn't wanna do it as such.
@andrewDev15 What "name" string? Did you mean the field called string? Is that supposed to be the "name"? You didn't show whether that field is returned by a getString(), getName(), or toString() method. Assuming the last, which is not a bad assumption given the name of the field, this code does what you want. Perhaps you show give better code in the question, if you want to clarify differently.

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.