69

How can I get the name of a Java Enum type given its value?

I have the following code which works for a particular Enum type, can I make it more generic?

public enum Category {

    APPLE("3"), 
    ORANGE("1"), 

    private final String identifier;

    private Category(String identifier) {
        this.identifier = identifier;
    }

    public String toString() {
        return identifier;
    }

    public static String getEnumNameForValue(Object value){
        Category[] values = Category.values();
        String enumValue = null;
        for(Category eachValue : values) {
            enumValue = eachValue.toString();

            if (enumValue.equalsIgnoreCase(value)) {
                return eachValue.name();
            }
        }
        return enumValue;
    }
}
2
  • 3
    Is there a special reason why you want to use something other than the name() of the Enum for looking them up? That would confuse a lot of people, and you also cannot use a simple Category.valueOf(name). Commented Oct 8, 2010 at 9:36
  • Really can we make it more generic? I am using a lot of nameOf(String name), now for each I will write a *Enum.values().stream().filter(...).findAny().get(), which is so annoying. Commented May 18, 2018 at 12:33

7 Answers 7

60

You should replace your getEnumNameForValue by a call to the name() method.

Sign up to request clarification or add additional context in comments.

5 Comments

@Jukia: Also, consider overriding toString(): download.oracle.com/javase/6/docs/api/java/lang/…
@trashgod: She is overriding toString
@Thilo: My error; thanks. @Julia: Sorry about misspelling your name.
@trashgod: Julia wanted to pass the value. How to pass the value as parameter in name() function ?
@kayeshparvez: I've used a Map of values(), as discussed here.
49

Try below code

public enum SalaryHeadMasterEnum {

    BASIC_PAY("basic pay"),
    MEDICAL_ALLOWANCE("Medical Allowance");

    private String name;

    private SalaryHeadMasterEnum(String stringVal) {
        name=stringVal;
    }
    public String toString(){
        return name;
    }

    public static String getEnumByString(String code){
        for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
            if(e.name.equals(code)) return e.name();
        }
        return null;
    }
}

Now you can use below code to retrieve the Enum by Value

SalaryHeadMasterEnum.getEnumByString("Basic Pay")

Use Below code to get ENUM as String

SalaryHeadMasterEnum.BASIC_PAY.name()

Use below code to get string Value for enum

SalaryHeadMasterEnum.BASIC_PAY.toString()

3 Comments

code == e.name is not going to work the way you meant it to, should be e.name.equals(code) instead
Well, yes: SalaryHeadMasterEnum.getEnumByString("basic pay") does work, but relies on the JVM merging String literals. Stuff like SalaryHeadMasterEnum.getEnumByString(new StringBuilder("basic ").append("pay").toString()) does not, but should IMHO. Using String.equals() would make both work ;-)
- for comparing strings with == which is bad and for using a variable 'name' with a different meaning than the 'name()' method
5

Try, the following code..

    @Override
    public String toString() {
    return this.name();
    }

1 Comment

This should work well, but why call the function toString() instead of getName() (Or something similar) ?
1

Here is the below code, it will return the Enum name from Enum value.

public enum Test {

    PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
            "DivideByZero");
    private String operationName;

    private Test(final String operationName) {
        setOperationName(operationName);
    }

    public String getOperationName() {
        return operationName;
    }

    public void setOperationName(final String operationName) {
        this.operationName = operationName;
    }

    public static Test getOperationName(final String operationName) {

        for (Test oprname : Test.values()) {
            if (operationName.equals(oprname.toString())) {
                return oprname;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return operationName;
    }
}

public class Main {
    public static void main(String[] args) {

        Test test = Test.getOperationName("Plus One");
        switch (test) {
        case PLUS:
            System.out.println("Plus.....");
            break;
        case MINUS:
            System.out.println("Minus.....");
            break;

        default:
            System.out.println("Nothing..");
            break;
        }
    }
}

Comments

1

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

1 Comment

A "NullPointerException" could be thrown; "orElse()" can return null in case of "When you want to find with name:" flow.
1
enum MyEnum {
    ENUM_A("A"),
    ENUM_B("B");

    private String name;
   
    private static final Map<String,MyEnum> unmodifiableMap;

    MyEnum (String name) {
        this.name = name;
    }

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

    static {
        Map<String,MyEnum> map = new ConcurrentHashMap<String, MyEnum>();
        for (MyEnum instance : MyEnum.values()) {
            map.put(instance.getName().toLowerCase(),instance);
        }
        unmodifiableMap = Collections.unmodifiableMap(map);
    }
    public static MyEnum get (String name) {
        return unmodifiableMap.get(name.toLowerCase());
    }
}

Now you can use below code to retrieve the Enum by Value

MyEnum.get("A");

Comments

0

I believe it's better to provide the required method in the enum itself. This is how I fetch Enum Name for a given value. This works for CONSTANT("value") type of enums.

public enum WalletType {
    UPI("upi-paymode"),
    PAYTM("paytm-paymode"),
    GPAY("google-pay");

    private String walletType;
        WalletType(String walletType) {
            this.walletType = walletType;
        }
    
    public String getWalletType() {
        return walletTypeValue;
    }
    
    public WalletType getByValue(String value) {
        return Arrays.stream(WalletType.values()).filter(wallet -> wallet.getWalletType().equalsIgnoreCase(value)).findFirst().get();
    }
}

e.g. WalletType.getByValue("google-pay").name() this will give you - GPAY

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.