Java: Check String is an Enum Constant

Following is how you can check if a string is an Enum constant.
This is often needed if you get User input as a string and want to call a method that requires an enum.
I post this here as I don’t want to search the web for it, as there you often get a stackoverflow answer which is not as performant as the code below. Now I can just grab it from my own blog.

/******************************************************************************
 * 
 ******************************************************************************/
public enum MyEnum {
	  TIRAMISU 
	, PANNA_COTTA
	, ICE_CREAM
	;
	
	private static HashSet<String> names = new HashSet<>();
	static {
		for(MyEnum type : MyEnum.values()) { names.add(type.name()); }
	}

	public static boolean has(String value) { return names.contains(value); }
}	
	

Share:


enumjava

Leave a Reply

Your email address will not be published.