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?
The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.
In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum.
You can create a list that holds enum instances just like you would create a list that holds any other kind of objects: ? List<ExampleEnum> list = new ArrayList<ExampleEnum>(); list.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With