Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking up enum label by value

I have the following enum in my java android application:

static enum PaymentType
{           
    Scheme(0), Topup(1), Normal(2), Free(3), Promotion(4), Discount(5), Partial(6),
    Refund(7), NoShow(8), Prepay(9), Customer(10), Return(11), Change(12), PettyCash(13),
    StateTax(14), LocalTax(15), Voucher(16), Membership(17), Gratuity(18), Overpayment(19),
    PrepayTime(20), HandlingFee(21);

    private int value;

    private PaymentType(int i) {
        value = i;
    }
    public int getValue() {
        return value;
    }
}

I use this enum alot to find out the integer value of one of these string labels, for example int i = Lookups.PaymentType.Voucher.getValue();.

How can I do this the other way around? I have an integer value from a database and I need to find which string that corresponds to.

like image 406
Mike Baxter Avatar asked Sep 19 '13 10:09

Mike Baxter


1 Answers

You should do something like this (static-init block should be at the end! and in your case just replace "asc" and "desc" with numbers, or add any other field):

public enum SortOrder {
    ASC("asc"),
    DESC("desc");

    private static final HashMap<String, SortOrder> MAP = new HashMap<String, SortOrder>();

    private String value;

    private SortOrder(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    public static SortOrder getByName(String name) {
        return MAP.get(name);
    }

    static {
        for (SortOrder field : SortOrder.values()) {
            MAP.put(field.getValue(), field);
        }
    }
}

After that, just call:

SortOrder asc = SortOrder.getByName("asc");
like image 185
kovrik Avatar answered Sep 22 '22 19:09

kovrik