Skip to content

Instantly share code, notes, and snippets.

@akutz
Created March 13, 2013 12:47
Show Gist options
  • Save akutz/5151745 to your computer and use it in GitHub Desktop.
Save akutz/5151745 to your computer and use it in GitHub Desktop.
A performant way of testing enum membership and parsing an enum from text.
public enum FuBar
{
ONE("one"),
TWO("two");
private static final String PATT;
private static final Map<String,FuBar> MAP;
static
{
MAP = new HashMap<String,FuBar>();
StringBuilder sb = new StringBuilder("(?i)");
for (FuBar e : FuBar.values())
{
if (sb.length() > 4)
{
sb.append("|");
}
sb.append(e);
MAP.put(e.toString().toUpperCase(), e);
}
}
private final String value;
private FuBar(String value)
{
this.value = value;
}
public boolean isFuBar(String text)
{
if (text == null)
{
throw new IllegalArgumentException("text is null");
}
return text.matches(PATT);
}
public FuBar parse(String text)
{
if (!isFuBar(text))
{
return null;
}
return MAP[text.toUpperCase()];
}
@Override
public String toString()
{
return this.value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment