title: The proper way to look up an enum by value
body: <p>I have several Java enums that looks something like below (edited for confidentiality, etc). 
  In each case, I have a lookup method that I'm really not satisfied with; in the example below, it is <code>findByChannelCode</code>.  </p>
  
  <pre><code>public enum PresentationChannel {
      ChannelA("A"),
      ChannelB("B"),
      ChannelC("C"),
      ChannelD("D"),
      ChannelE("E");
  
      private String channelCode;
  
      PresentationChannel(String channelCode) {
          this.channelCode = channelCode;
      }
  
      public String getChannelCode() {
          return this.channelCode;
      }
  
      public PresentationChannel findByChannelCode(String channelCode) {
          if (channelCode != null) {
              for (PresentationChannel presentationChannel : PresentationChannel.values()) {
                  if (channelCode.equals(presentationChannel.getChannelCode())) {
                      return presentationChannel;
                  }
              }
          }
  
          return null;
      }
  }
  </code></pre>
  
  <p>The problem is, I feel silly doing these linear lookups when I could just be using a <code>HashMap&lt;String, PresentationChannel&gt;</code>. So I thought of the solution below, but it's a little messier that I would hope and, more to the point, I didn't care to re-invent the wheel when surely someone else has come across this. I wanted to get some of the sage wisdom of this group: <em>what is the proper way to index an enum by value?</em></p>
  
  <p>My solution:</p>
  
  <pre><code>ImmutableMap&lt;String, PresentationChannel&gt; enumMap = Maps.uniqueIndex(ImmutableList.copyOf(PresentationChannel.values()), new Function&lt;PresentationChannel, String&gt;() {
          public String apply(PresentationChannel input) {
              return input.getChannelCode();
          }});
  </code></pre>
  
  <p>and, in the enum:</p>
  
  <pre><code>public static PresentationChannel findByChannelCode(String channelCode) {
       return enumMap.get(channelCode);
  }
  </code></pre>