How to convert a String to an Enum

The other day I was asked how to take an input string and convert it into an enum.  The individual in question searched the nets to no avail…so, this seemed like a good opportunity to impart some knowledge that is apparently hard to find.

public enum Fruit {
  APPLE("apple"), BANANA("banana"), PEAR("pear");

  private String fruitName;

  private Fruit(String fruitName) {
    this.fruitName = fruitName;
  }

  public convertToEnum(String stringToConvert) {
    for(Fruit fruit: Fruit.values()) {
      if(fruit.fruitName.equalsIgnoreCase(stringToConvert)) {
        return fruit;
      }
      return null;
    }
  }
}

In words, we construct our Enum with strings that represent the particular enum (you could probably get away with just using the name of the enum, rather than adding the string representation).  Then you simply create a convert method that can loop through the values of the enum (which is all of the enumerated values defined, in this case APPLE, BANANA and PEAR), and compare the string sent in to the string representation ignoring case and return the matching enum.

By accessing the enum.values(), you can easily add additional enumerated values without changing any of the rest of the Enum.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s