How can I get the names as a List<String> or Set<String> given the Enums?

132 views Asked by At

For example:

    public enum Day {
        MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY;
    }

Given the Enums MONDAY, WEDNESDAY, SATURDAY, I could get the List or Set in which the elements are ["monday", "wednesday", "saturday"]. Any methods in Java? Or any other Util classes?

2

There are 2 answers

1
Stewart On

Java 8

Arrays.stream(Day.values()).map( (v) -> v.name()).collect(Collectors.toList());

Pre-Java 8

List<String> list = new ArrayList<>();
for( Day day : Day.values() )  {
    list.add( day.name() );
}
2
Ismail On

You can use the method values() of the enumeration type, it returns an array with the enumeration values:

Day.values();

If you would like to transform the array to a list of strings, you simply need to do the following:

Arrays.stream(Day.values()).map( (v) -> v.name()).collect(Collectors.toList());