Algorithm


  1. Define the Enum:

    • Declare the enum with constants.
  2. Create a Method for Iteration:

    • Define a method to iterate over the enum.
  3. Use values() Method:

    • Call the values() method on the enum to get an array of constants.
  4. Iterate Over the Array:

    • Use a loop (e.g., enhanced for loop) to iterate over the array.
  5. Process Each Enum Constant:

    • Perform actions for each enum constant inside the loop.
  6. Example:

    • Output or process each enum constant as needed.

 

Code Examples

#1 Code Example- Loop through enum using forEach loop

Code - Java Programming

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 + ", ");
    }
  }
 }
Copy The Code & Try With Live Editor

Output

x
+
cmd
Access each enum constants
SMALL, MEDIUM, LARGE, EXTRALARGE,

#2 Code Example- Loop through enum using EnumSet Class

Code - Java Programming

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 + ", ");
    }

  }
 }
Copy The Code & Try With Live Editor

Output

x
+
cmd
Elements of EnumSet:
SMALL, MEDIUM, LARGE, EXTRALARGE,
Advertisements

Demonstration


Java Programing Example to Iterate over enum-DevsEnv