EnumUtil

Introduction

Enums (enumerations) are considered a “syntactic sugar” that refers to a sorted list of items packaged as a single entity. An instance of an enum can use any single value from the enum’s list. Enums are widely used in various languages, typically to represent limited, discrete, and explicitly expressed quantities such as colors, styles, categories, states, etc. Java introduced support for enums starting from JDK5.

EnumUtil is used to operate on unknown enum types.

Methods

First, we define an enum object:

// Defines an enum
public enum TestEnum{
	TEST1("type1"), TEST2("type2"), TEST3("type3");
	
	private TestEnum(String type) {
		this.type = type;
	}
	
	private String type;
	
	public String getType() {
		return this.type;
	}
}

getNames

Gets a list of names of all enum objects in the enum class. Example:

List<String> names = EnumUtil.getNames(TestEnum.class);
// Result: [TEST1, TEST2, TEST3]

getFieldValues

Obtains the values of a specific field for each enum object in the enum class. Example:

List<Object> types = EnumUtil.getFieldValues(TestEnum.class, "type");
// Result: [type1, type2, type3]

getBy

Gets the enum corresponding to the provided lambda and value. Example:

TestEnum testEnum = EnumUtil.getBy(TestEnum::ordinal, 1);
// Result: TEST2

getFieldBy

Gets the value of the enum corresponding to the provided lambda and value. Example:

String type = EnumUtil.getFieldBy(TestEnum::getType, Enum::ordinal, 1);
// Result: "type2"

getEnumMap

Gets a map with string enum values and their corresponding enum objects using a LinkedHashMap to maintain order, with keys as enum names and values as enum objects. Example:

Map<String,TestEnum> enumMap = EnumUtil.getEnumMap(TestEnum.class);
enumMap.get("TEST1") // Result: TestEnum.TEST1

getNameFieldMap

Gets a map with enum names corresponding to the specified field values, with keys as enum names and values as field values. Example:

Map<String, Object> enumMap = EnumUtil.getNameFieldMap(TestEnum.class, "type");
enumMap.get("TEST1") // Result: type1