Getting all names in an enum as a String[]

前端 未结 21 1194
执笔经年
执笔经年 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:44

    The easiest way:

    Category[] category = Category.values();
    for (int i = 0; i < cat.length; i++) {
         System.out.println(i  + " - " + category[i]);
    }
    

    Where Category is Enum name

    0 讨论(0)
  • 2020-12-01 04:45

    If you can use Java 8, this works nicely (alternative to Yura's suggestion, more efficient):

    public static String[] names() {
        return Stream.of(State.values()).map(State::name).toArray(String[]::new);
    }
    
    0 讨论(0)
  • 2020-12-01 04:46

    Just a thought: maybe you don't need to create a method to return the values of the enum as an array of strings.

    Why do you need the array of strings? Maybe you only need to convert the values when you use them, if you ever need to do that.

    Examples:

    for (State value:values()) {
        System.out.println(value); // Just print it.
    }
    

    for (State value:values()) {
        String x = value.toString(); // Just iterate and do something with x.
    }
    

    // If you just need to print the values:
    System.out.println(Arrays.toString(State.values()));
    
    0 讨论(0)
  • 2020-12-01 04:48

    Create a String[] array for the names and call the static values() method which returns all the enum values, then iterate over the values and populate the names array.

    public static String[] names() {
        State[] states = values();
        String[] names = new String[states.length];
    
        for (int i = 0; i < states.length; i++) {
            names[i] = states[i].name();
        }
    
        return names;
    }
    
    0 讨论(0)
  • 2020-12-01 04:48

    Here`s an elegant solution using Apache Commons Lang 3:

    EnumUtils.getEnumList(State.class)
    

    Although it returns a List, you can convert the list easily with list.toArray()

    0 讨论(0)
  • 2020-12-01 04:48

    You can put enum values to list of strings and convert to array:

        List<String> stateList = new ArrayList<>();
    
                for (State state: State.values()) {
                    stateList.add(state.toString());
                }
    
        String[] stateArray = new String[stateList.size()];
        stateArray = stateList.toArray(stateArray);
    
    0 讨论(0)
提交回复
热议问题