πŸ” Java How-To Examples
Estimated reading: 3 minutes 28 views

πŸ” Loop Through an Enum in Java – Complete Guide with Examples

🧲 Introduction

Java enum (short for enumeration) defines a fixed set of constants. You often use enums to represent days of the week, directions, states, etc.

But how do you loop through all values of an enum?

In this article, you’ll learn:

  • βœ… How to iterate over enum constants
  • βœ… Use cases of looping enums (like menus, logic flows)
  • βœ… Tips for adding fields/methods in enums

πŸ”‘ What is an Enum in Java?

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

πŸ“˜ Day is an enum representing the days of the week.


πŸ” Looping Through Enum Values (Using values())

for (Day day : Day.values()) {
    System.out.println(day);
}

βœ… Explanation:

  • Day.values() returns an array of all constants in the enum.
  • The enhanced for loop prints each value.

πŸ’‘ Best practice for looping through enums.


πŸ’‘ Example: Enum with Switch Case Logic

for (Day day : Day.values()) {
    switch (day) {
        case MONDAY:
            System.out.println("Start of the week!");
            break;
        case FRIDAY:
            System.out.println("Almost weekend!");
            break;
        case SUNDAY:
            System.out.println("Rest day!");
            break;
        default:
            System.out.println(day + " is a regular day.");
    }
}

βœ… Shows how enums integrate with control flows.


βš™οΈ Loop Through Enum with Fields

You can add custom fields/methods to enums:

public enum Planet {
    MERCURY(3.303e+23), VENUS(4.869e+24), EARTH(5.976e+24);

    private final double mass;

    Planet(double mass) {
        this.mass = mass;
    }

    public double getMass() {
        return mass;
    }
}

πŸ” Loop with Custom Data:

for (Planet p : Planet.values()) {
    System.out.println(p + " has mass " + p.getMass());
}

βœ… Useful in real-world simulations and config-driven systems.


πŸ“‹ Enum Looping Comparison Table

Loop StyleDescriptionUse Case
for (E e : Enum.values())Standard enum loopMost common usage
Stream.of(Enum.values())Java 8 stream-based loopingFiltering, mapping, collecting
EnumSet.allOf(Enum.class)Efficient set-based enum iterationFast, memory-efficient enum sets

⚑ Advanced: Using EnumSet for Efficient Loops

import java.util.EnumSet;

EnumSet<Day> workDays = EnumSet.range(Day.MONDAY, Day.FRIDAY);

for (Day day : workDays) {
    System.out.println(day + " is a workday.");
}

βœ… EnumSet is highly optimized for enum collections.


πŸ“Œ Summary

You now know how to:

  • βœ… Loop through enums using .values()
  • βœ… Use enums in switch cases and with custom fields
  • βœ… Optimize enum loops with EnumSet and Java Streams

Mastering enum iteration will help you build more readable, type-safe, and efficient Java applications.


❓FAQ – Looping Enums in Java

❓Can I get the number of enum constants?

int total = Day.values().length;
System.out.println("Total days: " + total);

βœ… Yes, use .length on the result of values().


❓Can I use streams to loop enums?

Arrays.stream(Day.values())
      .filter(day -> day.toString().startsWith("S"))
      .forEach(System.out::println);

βœ… Perfect for filtering or functional-style processing (Java 8+).


❓What if I want to associate descriptions or values with enums?

Add fields and a constructor, like:

public enum Status {
    ACTIVE("A"), INACTIVE("I");

    private String code;
    Status(String code) { this.code = code; }
    public String getCode() { return code; }
}

Loop through:

for (Status s : Status.values()) {
    System.out.println(s + " = " + s.getCode());
}

Share Now :

Leave a Reply

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

Share

Loop Through an Enum

Or Copy Link

CONTENTS
Scroll to Top