how to get enum id using its enum name

12.8k Views Asked by At
public enum EnumCountry implements EnumClass<Integer> {

  Ethiopia(1),
  Tanzania(2),
  private Integer id;

  EnumCountry(Integer value) {
    this.id = value;
  }

  public Integer getId() {
    return id;
  }

  @Nullable
  public static EnumCountry fromId(Integer id) {
    for (EnumCountry at : EnumCountry.values()) {
      if (at.getId().equals(id)) {
        return at;
      }
    }
    return null;
  }
}

I have the code like above. How can I get Enum Id using its Enum Name.

4

There are 4 best solutions below

0
Neil On

It is as simple as calling its getId() method:

Ethiopia.getId()

Or:

Tanzania.getId()

Or, assuming you meant you have the string "Ethiopia", then you can also do EnumCountry.valueOf("Ethiopia").getId(). Hope that answers your question!

0
shakhawat On

You can simply add a method like below -

  public static int getId(String enumCountryName) {
     return EnumCountry.valueOf(enumCountryName).getId();
  }

So the complete class will be like this -

public enum EnumCountry implements EnumClass<Integer> {

  Ethiopia(1),
  Tanzania(2);
  private Integer id;

  EnumCountry(Integer value) {
    this.id = value;
  }

  public Integer getId() {
    return id;
  }

  @Nullable
  public static EnumCountry fromId(Integer id) {
    for (EnumCountry at : EnumCountry.values()) {
      if (at.getId().equals(id)) {
        return at;
      }
    }
    return null;
  }

 public static int getId(String enumCountryName) {
     return EnumCountry.valueOf(enumCountryName).getId();
  }
}
0
Tamas Rev On

You can't because their types are incompatible - i.e. String vs Integer. On the other hand, you can add a method that returns a String that combines name and id:

public enum EnumCountry implements EnumClass<Integer> {

  Ethiopia(1),
  Tanzania(2); // replaced comma with semicolon

  private Integer id;

  // ...

  public String getNameId() {
      // returns "Ethiopa 1"
      return name() + " " + id;
  }

  // ...
}
0
Amber Beriwal On

If name is present as String, simply do this,

int getId(String name){
  EnumCountry country = EnumCountry.valueOf(name);
  return country.getId();
}