Filling a List with all enum values in Java

81

I would like to fill a list with all possible values of an enum
Since I recently fell in love with EnumSet, I leveraged allOf()

EnumSet<Something> all = EnumSet.allOf( Something.class);
List<Something> list = new ArrayList<>( all.size());
for (Something s : all) {
    list.add( s);
}
return list;

Is there a better way (as in non obfuscated one liner) to achieve the same result?

This question is tagged with java list enums

~ Asked on 2013-04-22 14:02:17

The Best Answer is


171

I wouldn't use a List in the first places as an EnumSet is more approriate but you can do

List<Something> somethingList = Arrays.asList(Something.values());

or

List<Something> somethingList =
                 new ArrayList<Something>(EnumSet.allOf(Something.class));

~ Answered on 2013-04-22 14:05:01


12

Class.getEnumConstants()

List<SOME_ENUM> enumList = Arrays.asList(SOME_ENUM.class.getEnumConstants());

~ Answered on 2014-12-25 09:08:23


Most Viewed Questions: