Write a Java Program to Iterate over enum

Java Program to Iterate over enum

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Iterate over enum
Java Program to Iterate over enum

Write a Java Program to Iterate over enum

PROGRAM: Java Program to Iterate over enum

/*Java Program to Iterate over enum*/

1: Loop through enum using forEach loop

enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}

class Main {
public static void main(String[] args) {

System.out.println(“Access each enum constants”);

// use foreach loop to access each value of enum
for(Size size : Size.values()) {
System.out.print(size + “, “);
}
}
}

2: Loop through enum using EnumSet Class

import java.util.EnumSet;
// create an enum
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}

class Main {
public static void main(String[] args) {

// create an EnumSet class
// convert the enum Size into the enumset
EnumSet<Size> enumSet = EnumSet.allOf(Size.class);

System.out.println(“Elements of EnumSet: “);
// loop through the EnumSet class
for (Size constant : enumSet) {
System.out.print(constant + “, “);
}

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *