简体   繁体   English

从枚举值生成数组

[英]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" 生成包含枚举字符串值的String[]数组的最佳方法是什么,即"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 Fruit.getName()将是一个返回Enum中string字段的方法

你可能会做这样的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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