Tuesday 12 July 2022

How to get all the enum keys or constants in Java?

Approach 1: Using ‘EnumSet.allOf’ method.

EnumSet<Day> dayEnums = EnumSet.allOf(Day.class);
for (Day day : dayEnums) {
	System.out.println(day);
}

Approach 2: Using values() method of enum.

Day[] daysArray = Day.values();
for (Day day : daysArray) {
	System.out.println(day);
}


 

Find the below working application.

Day.java

package com.sample.app.constants;

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

App.java

package com.sample.app;

import java.util.EnumSet;

import com.sample.app.constants.Day;

public class App {
	public static void main(String[] args) {
		// Approach 1
		EnumSet<Day> dayEnums = EnumSet.allOf(Day.class);
		for (Day day : dayEnums) {
			System.out.println(day);
		}

		System.out.println();

		// Approach 2
		Day[] daysArray = Day.values();
		for (Day day : daysArray) {
			System.out.println(day);
		}

	}
}

Output

SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY


 

Previous                                                 Next                                                 Home

No comments:

Post a Comment