0

I have the following enum

public enum AppointmentSlotStatusType {

    INACTIVE(0), ACTIVE(1);

    private int value;

    private AppointmentSlotStatusType(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public String getName() {
        return name();
    }
}

How do I get the enum name if a value is known for instance 1 ?

abiieez
  • 3,139
  • 14
  • 57
  • 110

3 Answers3

6

For this specific enum it's easy

String name = TimeUnit.values()[1].name();
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

You can implement a public static method inside the enum, which will give you the enum instance for that id:

public static AppointmentSlotStatusType forId(int id) {
    for (AppointmentSlotStatusType type: values()) {
        if (type.value == id) {
            return value;
        }
    }
    return null;
}

Probably you would also like to cache the array returned by values() in a field:

public static final AppointmentSlotStatusType[] VALUES = values();

then use VALUES instead of values().


Or you can use a Map instead.

private static final Map<Integer, AppointmentSlotStatusType> map = new HashMap<>();

static {
    for (AppointmentSlotStatusType type: values()) {
        map.put(type.value, type);
    }
}

public static AppointmentSlotStatusType forId(int id) {
    return map.get(id);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

You can maintain a Map to hold name for Integer key.

public enum AppointmentSlotStatusType {
    INACTIVE(0), ACTIVE(1);

    private int value;

    private static Map<Integer, AppointmentSlotStatusType> map = new HashMap<Integer, AppointmentSlotStatusType>();

    static {
        for (AppointmentSlotStatusType item : AppointmentSlotStatusType.values()) {
            map.put(item.value, item);
        }
    }

    private AppointmentSlotStatusType(final int value) { this.value = value; }

    public static AppointmentSlotStatusType valueOf(int value) {
        return map.get(value);
    }
}

Take a look at this answer.

Community
  • 1
  • 1
BobTheBuilder
  • 18,858
  • 6
  • 40
  • 61
  • 4
    Why not just vote to close this as a duplicate? Where do you see the difference between this question and the one you linked to? – Jon Skeet Oct 15 '13 at 15:43