Getting all names in an enum as a String[]

前端 未结 21 1429
执笔经年
执笔经年 2020-12-01 03:50

What\'s the easiest and/or shortest way possible to get the names of enum elements as an array of Strings?

What I mean by this is that if, for example,

21条回答
  •  我在风中等你
    2020-12-01 04:28

    Here's one-liner for any enum class:

    public static String[] getNames(Class> e) {
        return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
    }
    

    Pre Java 8 is still a one-liner, albeit less elegant:

    public static String[] getNames(Class> e) {
        return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
    }
    

    That you would call like this:

    String[] names = getNames(State.class); // any other enum class will work
    

    If you just want something simple for a hard-coded enum class:

    public static String[] names() {
        return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");
    }
    

提交回复
热议问题