Learnitweb

Iterating over Enum Values in Java

An enum type enables for a variable to be a set of predefined constants. To demonstrate iterating over enum values let us first declare one:

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

enum provides values() method which returns an array. We can then iterate this array of enum values like any other array.

Iterate using for-each loop

public class EnumIterateExample {
	public enum Days {
		SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
	}

	public static void main(String args[]) {
		Days[] days = Days.values();

		for (Days day : days) {
			System.out.println(day);
		}
	}
}

A shorter format of the above code could be:

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

Iterate Using java.util.stream

Iteration over enum can also be done using java.util.stream class. Create the stream of enum.values() using Stream.of() method by passing enum.values() at parameter to function. However, this tutorial is for Java 7 but we are including this java.util.stream of Java 8 as this makes sense to mention here.

import java.util.stream.Stream;

public class EnumIterateExample {
	public enum Days {
		SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
	}

	public static void main(String args[]) {
		Days[] days = Days.values();

		Stream.of(Days.values()).forEach(System.out::println);
	}
}

Itertor using Iterable forEach

You can convert array return by value() method to set or list and then use forEach to iterate over values.

import java.util.Arrays;
import java.util.EnumSet;

public class EnumIterateExample {
	public enum Days {
		SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
	}

	public static void main(String args[]) {
		Days[] days = Days.values();

		// Convert enum to set and apply forEach()
		EnumSet.allOf(Days.class).forEach(season -> System.out.println(season));

		// Convert enum to set and apply forEach()
		Arrays.asList(Days.values()).forEach(season -> System.out.println(season));
	}
}