membersound
membersound

Reputation: 86687

How to find an enum according to a value?

I'm working with a (legacy, not changeable) enum that looks like this:

enum MsgEnum {
   private int number;
   private int msg;

   MSG_OK("OK", 0);
   MSG_NOK("NOK, 1);
   //lots of other messages

   private MsgEnum(String msg, int number) {
      this.msg = msg;
      this.number = number;
   }
}

If I have the number, how could I best find out which MsgEnum matches the number (assuming they are unique)?

Is there any better way apart from the following?

class MyEnumHelper() {

    public static MsgEnum MsgEnumfromNumber(int number) {
        for (MsgEnum m : MsgEnum.values()) {
            if (m.getNumber() == number) {
                return m;
            }
        }
        return null;
    }
}

Upvotes: 0

Views: 203

Answers (1)

Julien
Julien

Reputation: 2584

You can declare a static Map in your Helper and access it using a static method getMsgEnumFromInteger(int). Something like :

private static final Map<Integer, MsgEnum> INT_TO_ENUM = new HashMap<Integer, MsgEnum>();

static {
    for (MsgEnum msgE : MsgEnum.values) {
        INT_TO_ENUM.put(msgE.getNumber(), msgE);
    }
}

public static MsgEnum getByInt(int number) {
    return INT_TO_ENUM.get(number);
}

(sorry if there are errors, it don't have a Java env at the moment ^^ )

Upvotes: 6

Related Questions