Java – enums | lookup enum by value


How to write lookup method in Java8

In Jdk8, above getEnum method can be written using lamdas or functional programming to iterate over values array. Below examples show how this method can be writted in different ways in jdk8. 

Method 1
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 public enum NumberEnum {      ONE(1),     TWO(2),     THREE(3);      private int value;      private NumberEnum(int value) {         this.value = value;     }      int value() {          return value;     }      public static NumberEnum getEnum(int value) {          Iterator<NumberEnum> iter = Arrays.stream(values()).iterator();         while(iter.hasNext()) {             NumberEnum numberEnum = iter.next();            if(numberEnum.value() == value) {                return numberEnum;            }         }         return null;     }  } 

 

Method 2 

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
 public enum NumberEnum {      ONE(1),     TWO(2),     THREE(3);      private int value;      private NumberEnum(int value) {         this.value = value;     }      int value() {         return value;     }     public static NumberEnum getEnum(int value) {              return Arrays.stream(values()).filter(e -> e.value() == (value)).findFirst().orElse(null);      }  } 

 

Performance difference between two approaches

Below section lists down the performance difference between two lookup approaches listed above i.e static lookup map vs lookup enum on the fly. These tests were performed on the dev machine running jdk8 and numbers could vary based on the system configuration. Approach is to find the worst time during enum lookup-

 

Static Map in init block        
Number of Constants Number of executions Min Time(ms) Max Time(ms) Avg (ms)
3 100 0 0 0
15 100 0 0 0
25 100 0 0 0
50 100 0 2 0
100 100 0 2 0
         
Runtime lookup        
Number of Constants Number of executions Min Time(ms) Max Time(ms) Avg (ms)
3 100 0 0 0
15 100 0 0 0
25 100 0 1 0
50 100 0 1 0
100 100 0 1 0

 

Conclusion

There is not much performance difference between two approaches. In static map approach too, key is different for all the values and static map has (n) number of keys for (n) enum constants being stored. Hence lookup timings are comparable in both the cases.  

Pages: 1 2 3

Leave a Reply

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