Java Iterating Over Enum values

In this tutorial, I am showing about enums iteration using different ways like forEach, stream and for loop.

A Java enum is a special data type which helps you to assign set of predefined constants to a variable

Iterate With forEach()

// iterate using forEach
	EnumSet.allOf(DaysOfWeek.class)
	  .forEach(day -> System.out.println(day));

Iterate With Stream

If you are using java 8 you can use streams for enum iteration

// iterate using stream
	Stream.of(DaysOfWeek.values()).forEach(System.out::println);

Iterate With for loop

You can use java for loop, if you are using old version of java

// iterate using for
	for (DaysOfWeek day : DaysOfWeek.values()) { 
	    System.out.println(day); 
	}


You can find the complete example of iterating enums below with all the above described ways.

package com.javatips;

import java.util.EnumSet;
import java.util.stream.Stream;

public class EnumsIteration {

    public enum DaysOfWeek {
	SUNDAY, MONDAY, TUESDAY, WEBNESDAY, THRUSDAY, FRIDAY, SATURDAY
    }

    public static void main(String[] args) {
	// iterate using forEach
	EnumSet.allOf(DaysOfWeek.class)
	  .forEach(day -> System.out.println(day));

	// iterate using stream
	Stream.of(DaysOfWeek.values()).forEach(System.out::println);
	
	// iterate using for
	for (DaysOfWeek day : DaysOfWeek.values()) { 
	    System.out.println(day); 
	}

	
    }

}


Output

SUNDAY
MONDAY
TUESDAY
WEBNESDAY
THRUSDAY
FRIDAY
SATURDAY
SUNDAY
MONDAY
TUESDAY
WEBNESDAY
THRUSDAY
FRIDAY
SATURDAY
SUNDAY
MONDAY
TUESDAY
WEBNESDAY
THRUSDAY
FRIDAY
SATURDAY












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