10

I have an Enum:

public enum Type {

    ADMIN(1), 
    HIRER(2), 
    EMPLOYEE(3);

    private final int id;

    Type(int id){
        this.id = id;       
    }

    public int getId() {
        return id;
    }
}

How can I get a Type enum passing an id property?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Maria
  • 233
  • 3
  • 13

3 Answers3

8

You can build a map to do this lookup.

static final Map<Integer, Type> id2type = new HashMap<>();
static {
    for (Type t : values())
        id2type.put(t.id, t);
}
public static Type forId(int id) {
    return id2type.get(id);
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Create a method inside the Type class returning the Enum instances:

Type get(int n) {
    switch (n) {
    case 1:
        return Type.ADMIN;
    case 2:
        return Type.EMPLOYEE;
    case 3:
        return Type.HIRER;
    default:
        return null;
    }

}

TIP: you need to add default in switch-case or add a return null at the end of the method to avoid compiler errors.


UPDATE (thanks to @AndyTurner):

It would be better to loop and refer to the id field, so you're not duplicating the IDs.

Type fromId(int id) {
    for (Type t : values()) {
        if (id == t.id) {
            return t;
        }
    }
    return null;
}
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

Try this out. I have created a method which searches type using id:

public static Type getType(int id) {

    for (Type type : Type.values()) {
        if (id == type.getId()) {
            return type;
        }
    }
    return null;
}