In this java example, we will demonstrate how to add values of an Enum to a List. This allows us to manipulate the List like any other.
Add Enum Values to ArrayList Example
import java.util.ArrayList;
import java.util.List;
public class EnumIterationExample {
public static void main(String[] args) {
System.out.println("Add Enum values to ArrayList:");
List < DaysOfWeekEnum > days = new ArrayList < > ();
days.add(DaysOfWeekEnum.FRIDAY);
days.add(DaysOfWeekEnum.SATURDAY);
days.add(DaysOfWeekEnum.SUNDAY);
for (DaysOfWeekEnum day: days) {
System.out.println(day);
}
System.out.println("Remove SATURDAY from the list:");
days.remove(DaysOfWeekEnum.SATURDAY);
if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
System.out.println("Saturday is no longer in the list");
}
for (DaysOfWeekEnum day: days) {
System.out.println(day);
}
}
}
enum DaysOfWeekEnum {
SUNDAY("off"),
MONDAY("working"),
TUESDAY("working"),
WEDNESDAY("working"),
THURSDAY("working"),
FRIDAY("working"),
SATURDAY("off");
private String typeOfDay;
DaysOfWeekEnum(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public String getTypeOfDay() {
return typeOfDay;
}
public void setTypeOfDay(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
}
Output:
Add Enum values to ArrayList:
FRIDAY
SATURDAY
SUNDAY
Remove SATURDAY from the list:
Saturday is no longer in the list
FRIDAY
SUNDAY
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course