Java Data Type How to - Get enum by its inner field








Question

We would like to know how to get enum by its inner field.

Answer

import java.util.HashMap;
import java.util.Map;
//from w w  w .  j  a v  a2s.  co m
public class Main {
  public static void main(String[] args) {
    System.out.println(Value.findByKey(69)); 

    System.out.println(Value.values() == Value.values());
  }
}

enum Value {
  ONE(1), TWO(2), SIXTY_NINE(69);

  private final int number;

  Value(int number) {
    this.number = number;
  }
  private static final Map<Integer, Value> map;
  static {
    map = new HashMap<Integer, Value>();
    for (Value v : Value.values()) {
      map.put(v.number, v);
    }
  }
  public static Value findByKey(int i) {
    return map.get(i);
  }
}

The code above generates the following result.