Getting all names in an enum as a String[]

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

    Another ways :

    First one

    Arrays.asList(FieldType.values())
                .stream()
                .map(f -> f.toString())
                .toArray(String[]::new);
    

    Other way

    Stream.of(FieldType.values()).map(f -> f.toString()).toArray(String[]::new);
    
    0 讨论(0)
  • 2020-12-01 04:36

    Try this:

    public static String[] vratAtributy() {
        String[] atributy = new String[values().length];
        for(int index = 0; index < atributy.length; index++) {
            atributy[index] = values()[index].toString();
        }
        return atributy;
    }
    
    0 讨论(0)
  • 2020-12-01 04:37

    My solution, with manipulation of strings (not the fastest, but is compact):

    public enum State {
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    
        public static String[] names() {
            String valuesStr = Arrays.toString(State.values());
            return valuesStr.substring(1, valuesStr.length()-1).replace(" ", "").split(",");
        }
    }
    
    0 讨论(0)
  • 2020-12-01 04:41

    org.apache.commons.lang3.EnumUtils.getEnumMap(State.class).keySet()

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

    the ordinary way (pun intended):

    String[] myStringArray=new String[EMyEnum.values().length];
    for(EMyEnum e:EMyEnum.values())myStringArray[e.ordinal()]=e.toString();
    
    0 讨论(0)
  • 2020-12-01 04:44

    Very similar to the accepted answer, but since I learnt about EnumSet, I can't help but use it everywhere. So for a tiny bit more succinct (Java8) answer:

    public static String[] getNames(Class<? extends Enum<?>> e) {
      return EnumSet.allOf(e).stream().map(Enum::name).toArray(String[]::new);
    }
    
    0 讨论(0)
提交回复
热议问题