Tuesday 7 March 2023

How to get all the enum values in Java?

In this post, I am going to explain how to get all the enum values in Java.

 

Approach 1: Using EnumSet.allOf method.

‘EnumSet.allOf ‘ method return an enum set containing all of the elements in the specified element type.

Set<AppState> appStates = EnumSet.allOf(AppState.class);

Approach 2: Using Class#getEnumConstants method.

Class#getEnumConstants() method return all the elements of this enum class or null if this Class object does not represent an enum type.

AppState[] appStatesArr = AppState.class.getEnumConstants();
for(AppState appState: appStatesArr) {
	System.out.println(appState);
}

 

Approach 3: Using EnumClass.values() method.

AppState[] appStatesArr = AppState.values();
for(AppState appState: appStatesArr) {
	System.out.println(appState);
}

 

Find the below working application.

 

EnumValuesDemo.java

 

package com.sample.app;

import java.util.EnumSet;
import java.util.Set;

public class EnumValuesDemo {
	private static enum AppState {
		INIT, READY, RUNNING, ABORT;
	}

	public static void main(String[] args) {

		Set<AppState> appStates = EnumSet.allOf(AppState.class);
		System.out.println(appStates + "\n");

		AppState[] appStatesArr = AppState.class.getEnumConstants();
		for (AppState appState : appStatesArr) {
			System.out.println(appState);
		}
		System.out.println();

		appStatesArr = AppState.values();
		for (AppState appState : appStatesArr) {
			System.out.println(appState);
		}
		System.out.println();

	}

}

 

Output

[INIT, READY, RUNNING, ABORT]

INIT
READY
RUNNING
ABORT

INIT
READY
RUNNING
ABORT

 



You may like

Interview Questions

Constant folding in Java

Quick guide to assertions in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Implementation of Bag data structure in Java

Scanner throws java.util.NoSuchElementException while reading the input

No comments:

Post a Comment