Indexed Java 8 enums with gaps

This is an example enum for Java 8 that supports gaps in its indices is relatively fast for enums with a large amount of values:

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public enum TestEnum {
   VALUE1( 0 ),
   VALUE2( 2 ),
   VALUE3( 50 );
   
   private final Integer id_;
   private static Map< Integer, TestEnum > values_ = 
      Arrays.stream( TestEnum.values() ).collect( Collectors.toMap(e -> e.id_, e -> e) );;
   
   private TestEnum( int i ) { id_ = i; }
   public static TestEnum fromInteger( int i )
   {
      return values_.get( i );
   }
   
}

Leave a Reply

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