Java Enum Example

This tutorial will show how to use Enum in Java. It will show how to get enum instances code by name.


Create below Java Enum

package enums;
import java.util.LinkedHashMap;
import java.util.Map;
public enum JavaEnum {
	Start("STRT"), //
	Pending("PEND"), //
	InProgress("PRGS"), //
	Complete("COMP"), //
	Error("ERR");
	private final String code;
	private JavaEnum(final String code) {
		this.code = code;
	}
	private static final Map<String, String> WORKFLOW_NAME_CODE_MAP = new LinkedHashMap<>();
	static {
		for (JavaEnum be : JavaEnum.values()) {
			WORKFLOW_NAME_CODE_MAP.put(be.name(), be.code);
		}
	}
	public static String getCodeByName(String name) {
		return WORKFLOW_NAME_CODE_MAP.get(name);
	}
	public String getName() {
		return name();
	}
	@Override
	public String toString() {
		return name();
	}
}

Create below main class to test the above enum

package enums;
public class JavaEnumTest {
	public static void main(String[] args) {
		System.out.println("Complete Name: " + JavaEnum.Complete.getName());
		System.out.println("Complete Name: " + JavaEnum.Complete.toString());
		System.out.println("Complete Code: " + JavaEnum.getCodeByName(JavaEnum.Complete.toString()));
	}
}

Output

Complete Name: Complete
Complete Name: Complete
Complete Code: COMP

Thanks for reading.

Related posts

Leave a Comment