🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this post, we will learn how to iterate over an Enum using Stream in Java.
Let's use Stream to perform operations on the Enum values.
To create a Stream we have two options, one using Stream.of:
Stream.of(DaysOfWeekEnum.values());
Another, using Arrays.stream:
Arrays.stream(DaysOfWeekEnum.values());
DaysOfWeekEnum.java
Let's first create an Enum called DaysOfWeekEnum. Note that we are using Stream.of() method.
import java.util.stream.Stream;
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;
}
public static Stream < DaysOfWeekEnum > stream() {
return Stream.of(DaysOfWeekEnum.values());
}
}
EnumIterationExample.java
Let's write an example in order to print all the Enum values using the forEach() method:
public class EnumIterationExample {
public static void main(String[] args) {
System.out.println("Enum iteration using Stream:");
DaysOfWeekEnum.stream().forEach(System.out::println);
}
}
Output
Enum iteration using Stream:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Complete Example
import java.util.stream.Stream;
public class EnumIterationExample {
public static void main(String[] args) {
System.out.println("Enum iteration using Stream:");
DaysOfWeekEnum.stream().forEach(System.out::println);
}
}
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;
}
public static Stream < DaysOfWeekEnum > stream() {
return Stream.of(DaysOfWeekEnum.values());
}
}
Output:
Enum iteration using Stream:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Comments
Post a Comment
Leave Comment