English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input/output (I)/)

Java Reader/Writer

Java other topics

Java program to traverse enumeration

Comprehensive Java Examples

In this example, we will learn how to traverse enumeration elements in Java by converting enumeration to an array and enumeration set.

To understand this example, you should know the followingJava programmingTopic:

Example1: Use the forEach loop to traverse the enumeration

enum Size {
  SMALL, MEDIUM, LARGE, EXTRALARGE
 }
 class Main {
  public static void main(String[] args) {
    System.out.println("Access each enumeration constant");
    // Use the foreach loop to access each value of the enumeration
    for(Size size : Size.values()) {
      System.out.print(size + ", ");
    }
  }
 }

Output1

Access each enumeration constant
SMALL, MEDIUM, LARGE, EXTRALARGE,

In the above example, we have an enumeration named Size. Note the expression

Size.values()

Here, the values() method converts enumeration constants to an array of Size type. Then, we use the forEach loop to access each element of the enumeration.

Example2: Use EnumSet class to traverse enumeration

import java.util.EnumSet;
//Create an enumeration
enum Size {
  SMALL, MEDIUM, LARGE, EXTRALARGE
 }
 class Main {
  public static void main(String[] args) {
    //Create an EnumSet class
    //Convert enum Size to EnumSet
    EnumSet<Size> enumSet = EnumSet.allOf(Size.class);
    System.out.println("Elements of EnumSet: ");
    //Traverse EnumSet class
    for (Size constant : enumSet) {
      System.out.print(constant + ", ");
    }
  }
 }

Output Result

Elements of EnumSet: 
SMALL, MEDIUM, LARGE, EXTRALARGE,

Here, we use the allOf() method to create an EnumSet class from the enum Size. Then we use the forEach loop to access each element of the enumset class.

Comprehensive Java Examples