While programming in Java, there is a frequent requirement to check if an Enum contains a given String value. There are multiple ways to validate this. But I find the EnumUtils class of Apache Commons Lang the most convenient to use.

The EnumUtils class has a method called isValidEnum which takes as parameters the name of the Enum class and the String to be matched. It returns a boolean true if the String is contained in the Enum class, and a boolean false otherwise.

The following code snippet demonstrates the usage of EnumUtils.isValidEnum()

EnumUtilsDemo.java
package com.planetofbits;

import org.apache.commons.lang3.EnumUtils;

public class EnumUtilsDemo
{
	public static void main(String[] args)
	{
		// Is PY("Python") a part of the enum?
		System.out.println(EnumUtils.isValidEnum(MathCodes.class, "PY"));
		
		// Is CA("Calculus") a part of the enum?
		System.out.println(EnumUtils.isValidEnum(MathCodes.class, "CA"));
	}
}

enum MathCodes
{
	LA("Linear Algebra"), CA("Calculus"), PB("Probability");

	private String mathSubject;

	MathCodes(String mathSubject)
	{
		this.setMathSubject(mathSubject);
	}

	public String getMathSubject()
	{
		return mathSubject;
	}

	public void setMathSubject(String mathSubject)
	{
		this.mathSubject = mathSubject;
	}
}

Running the above code gives the following output:

false
true
How to check if an enum contains a given string
    

Comments, Questions or Suggestions: