Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

Java Enums are starting to become more prevalent. One problem that I found is that if you have some data and need to get the enum for that, then you have to write something custom. I had always done that by:

    public static MyEnum getBySomeValue(String someValue) {
        MyEnum myEnumTarget = null;
        for (MyEnum myEnum : MyEnum.values()) {
            if (myEnum.getSomeValue().equals(someValue)) {
                myEnumTarget = myEnum;
        return myEnumTarget;

I recently ran across a post that showed a better way. I tweaked his example a little to produce:

package com.bhsi.preregistration;

import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/** @author Norris Shelton */
public enum EmailFormat {

    private static final Map<String, EmailFormat> keys = new HashMap<String, EmailFormat>();
    static {
        for (EmailFormat emailFormat : EmailFormat.values()) {
            keys.put(emailFormat.key(), emailFormat);

    EmailFormat(String key) {
        this.key = key;

    private final String key;

    public String key() {
        return key;

     * Creates an instance of the email format.
     * @param key the string key of the email format
     * @return an email format type object
    public static EmailFormat keyOf(String key) {
        EmailFormat emailFormat = EmailFormat.NONE;
        if (StringUtils.isNotBlank(key)) {
            emailFormat = keys.get(key);
        return emailFormat;

I am favoring this implementation. It consumes a little bit more memory, but is more efficient during the lookup.

Notice line 38. In this case, there were entries in the database. I only cared about “H” and “T”, but the database also had nulls and empty strings. By writing the code the way I did, all of those become NONE and the real values are associated with the HTML and TEXT types.

February 23rd, 2011

Posted In: Java

Leave a Reply

Your email address will not be published. Required fields are marked *

WP to LinkedIn Auto Publish Powered By :