Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conveniently map between enum and int / String

People also ask

Can enum be used for mapping?

Overview. EnumMap is a Map implementation that exclusively takes Enum as its keys.

Can enum be used in HashMap?

In HashMap, we can use Enum as well as any other object as a key. It doesn't allow storing null key. It allows to store the null keys as well values, but there should be only one null key object and there can be any number of null values. HashMap internally uses the HashTable.

Can you map an enum JavaScript?

Using `map()` on JavaScript EnumsJavaScript doesn't support enums natively, but you can use POJOs to simulate vanilla JavaScript enums as shown below. function createEnum(values) { const enumObject = {}; for (const val of values) { enumObject[val] = val; } return Object.


enum → int

yourEnum.ordinal()

int → enum

EnumType.values()[someInt]

String → enum

EnumType.valueOf(yourString)

enum → String

yourEnum.name()

A side-note:
As you correctly point out, the ordinal() may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)


http://www.javaspecialists.co.za/archive/Issue113.html

The solution starts out similar to yours with an int value as part of the enum definition. He then goes on to create a generics-based lookup utility:

public class ReverseEnumMap<V extends Enum<V> & EnumConverter> {
    private Map<Byte, V> map = new HashMap<Byte, V>();
    public ReverseEnumMap(Class<V> valueType) {
        for (V v : valueType.getEnumConstants()) {
            map.put(v.convert(), v);
        }
    }

    public V get(byte num) {
        return map.get(num);
    }
}

This solution is nice and doesn't require 'fiddling with reflection' because it's based on the fact that all enum types implicitly inherit the Enum interface.


I found this on the web, it was very helpful and simple to implement. This solution was NOT made by me

http://www.ajaxonomy.com/2007/java/making-the-most-of-java-50-enum-tricks

public enum Status {
 WAITING(0),
 READY(1),
 SKIPPED(-1),
 COMPLETED(5);

 private static final Map<Integer,Status> lookup 
      = new HashMap<Integer,Status>();

 static {
      for(Status s : EnumSet.allOf(Status.class))
           lookup.put(s.getCode(), s);
 }

 private int code;

 private Status(int code) {
      this.code = code;
 }

 public int getCode() { return code; }

 public static Status get(int code) { 
      return lookup.get(code); 
 }

}


Seems the answer(s) to this question are outdated with the release of Java 8.

  1. Don't use ordinal as ordinal is unstable if persisted outside the JVM such as a database.
  2. It is relatively easy to create a static map with the key values.

public enum AccessLevel {
  PRIVATE("private", 0),
  PUBLIC("public", 1),
  DEFAULT("default", 2);

  AccessLevel(final String name, final int value) {
    this.name = name;
    this.value = value;
  }

  private final String name;
  private final int value;

  public String getName() {
    return name;
  }

  public int getValue() {
    return value;
  }

  static final Map<String, AccessLevel> names = Arrays.stream(AccessLevel.values())
      .collect(Collectors.toMap(AccessLevel::getName, Function.identity()));
  static final Map<Integer, AccessLevel> values = Arrays.stream(AccessLevel.values())
      .collect(Collectors.toMap(AccessLevel::getValue, Function.identity()));

  public static AccessLevel fromName(final String name) {
    return names.get(name);
  }

  public static AccessLevel fromValue(final int value) {
    return values.get(value);
  }
}

org.apache.commons.lang.enums.ValuedEnum;

To save me writing loads of boilerplate code or duplicating code for each Enum, I used Apache Commons Lang's ValuedEnum instead.

Definition:

public class NRPEPacketType extends ValuedEnum {    
    public static final NRPEPacketType TYPE_QUERY = new NRPEPacketType( "TYPE_QUERY", 1);
    public static final NRPEPacketType TYPE_RESPONSE = new NRPEPacketType( "TYPE_RESPONSE", 2);

    protected NRPEPacketType(String name, int value) {
        super(name, value);
    }
}

Usage:

int -> ValuedEnum:

NRPEPacketType packetType = 
 (NRPEPacketType) EnumUtils.getEnum(NRPEPacketType.class, 1);

You could perhaps use something like

interface EnumWithId {
    public int getId();

}


enum Foo implements EnumWithId {

   ...
}

That would reduce the need for reflection in your utility class.