Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Enum instance [duplicate]

Tags:

java

enums

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?

like image 639
Maria Avatar asked May 03 '16 15:05

Maria


1 Answers

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);
}
like image 142
Peter Lawrey Avatar answered Sep 25 '22 06:09

Peter Lawrey