Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a List with all enum values in Java

Tags:

java

list

enums

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?

like image 352
MonoThreaded Avatar asked Apr 22 '13 14:04

MonoThreaded


People also ask

How do I get a list of all enum values?

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.

Can we create list of enum in Java?

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.

Can you have an ArrayList of enums?

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.


1 Answers

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)); 
like image 109
Peter Lawrey Avatar answered Oct 09 '22 07:10

Peter Lawrey