简体   繁体   中英

Generating an array from enum values

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, ie "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.

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

你可能会做这样的事情。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM