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
27.1k8 gold badges73 silver badges113 bronze badges
3 Answers 3
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);
}
answered May 3, 2016 at 15:31
Peter Lawrey
535k83 gold badges770 silver badges1.2k bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
brimborium
I like this solution the most. It is clean and has the best performance for arbitrarily big enums.
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;
}
answered May 3, 2016 at 15:29
Jordi Castilla
27.1k8 gold badges73 silver badges113 bronze badges
8 Comments
Andy Turner
It would be better to loop and refer to the
id field, so you're not duplicating the IDs.Jordi Castilla
@AndyTurner updated answer... but... why you say I'm duplicating the id's? I'm missing something? or you mean write a line by each id??
Jordi Castilla
@brimborium yes, but that is Peter answer....
brimborium
@JordiCastilla I just saw. ;)
Peter Lawrey
Note: every time you call
values() it creates a new array of the enum values. It has to do this because it doesn't know if you are going to mutate it or not. |
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;
}
Comments
lang-java
Typevalues and look for yourid; or populate aMap<Integer, Type>.int idinstead of aString text.