Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating an array from enum values

Tags:

java

enums

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.

like image 930
andrewDev15 Avatar asked Jul 06 '26 17:07

andrewDev15


1 Answers

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

like image 196
Alvin L-B Avatar answered Jul 09 '26 07:07

Alvin L-B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!