Filling a List With All Enum Values in Java

Filling a List with all enum values in Java

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));

List of enum values in java

Yes it is definitely possible, but you will have to do

List<MyEnum> al = new ArrayList<MyEnum>();

You can then add elements to al: al.add(ONE) or al.add(TWO).

Make a list and initialize it to include all the values of an Enum

Arrays#asList returns a List that doesn't support add or remove elements since just wraps an array. Instead, create a new ArrayList and pass the result of Arrays#asList as parameter:

List<Direction> directions = new ArrayList<>(Arrays.asList(Direction.values()));

Getting all names in an enum as a String[]

Here's one-liner for any enum class:

public static String[] getNames(Class<? extends Enum<?>> e) {
return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}

Pre Java 8 is still a one-liner, albeit less elegant:

public static String[] getNames(Class<? extends Enum<?>> e) {
return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
}

That you would call like this:

String[] names = getNames(State.class); // any other enum class will work

If you just want something simple for a hard-coded enum class:

public static String[] names() {
return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");
}

Is it possible to loop through an enum to add every item to a list in java?

Create your List like

List<School> schools = new ArrayList<School>(Arrays.asList(School.values()));

If you use Arrays.asList(School.values()) , you cannot add anything to that list later and you'll end up with an Exception. From docs of asList() method

Returns a fixed-size list backed by the specified array.

If you create the way suggested, you are able to add further elements to it.

How to pull elements from an enum without getting repetitions

You could populate a list with all values from your Colour enum, shuffle, and then just access values sequentially:

List<Colour> colourList = Arrays.asList(Colour.values());
Collections.shuffle(colourList);

Then, just iterate the list and access the colors in order, which of course should be random since the collection was shuffled:

for (Colour c : colourList) {
// do something with c
}

You could also go with your current approach, and store the colors into a set, rather than an ArrayList. But the problem there is that you may draw a duplicate value any number of times, and the chances of that happening as the set increases in size will go up.



Related Topics



Leave a reply



Submit