Fill a List With All Enum Values in Java

06 May 2023 Balmiki Mandal 0 Core Java

Filling a List With All Enum Values in Java

Java enum types provide a great way to define a set of related constants that can be used in code. But sometimes you may need to work with a list of all the possible enum values, or iterate over them. Fortunately, Java provides a few ways to do this.

Using Enum.values() method

The simplest and most common way to get a list of all possible enum values is to use the Enum.values() method. This method returns an array of all enum constants, which you can then easily convert into a list using the Arrays.asList() method.

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

// Get array of enum constants
Day[] days = Day.values();

// Convert it to a list
List<Day> list = Arrays.asList(days);

Using a for loop

Another way to get all enum values is to iterate over the enum type directly. Here's an example of how to do this using a for loop:

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

// Create a list object
List<Day> list = new ArrayList<>();

// Iterate over enum constants and add them to list
for (Day day : Day.values()) {
    list.add(day);
}

Using Streams API

If you are using Java 8 or higher, you can even use the Streams API to get a list of all enum values. Here's an example of how to do this:

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

// Convert enum to a list
List<Day> list = Stream.of(Day.values())
                        .collect(Collectors.toList());

As you can see, there are a few different ways to fill a list with all enum values in Java. So pick the one that works best for your particular situation.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.