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
27.1k8 gold badges73 silver badges113 bronze badges
asked May 3, 2016 at 15:26
2
  • 3
    You could iterate the Type values and look for your id; or populate a Map<Integer, Type>. Commented May 3, 2016 at 15:27
  • This might be exactly what you need. (except that you have an int id instead of a String text. Commented May 3, 2016 at 15:30

3 Answers 3

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution the most. It is clean and has the best performance for arbitrarily big enums.
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;
}
answered May 3, 2016 at 15:29

8 Comments

It would be better to loop and refer to the id field, so you're not duplicating the IDs.
@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??
@brimborium yes, but that is Peter answer....
@JordiCastilla I just saw. ;)
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.
|
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;
}
answered May 3, 2016 at 16:06

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.