1
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.

Flown
  • 11,480
  • 3
  • 45
  • 62
user7360
  • 11
  • 1
  • 1
  • 4
  • 1
    Possible duplicate of https://stackoverflow.com/questions/604424/lookup-enum-by-string-value – wds Oct 10 '17 at 06:45

4 Answers4

9

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();
  }
}
shakhawat
  • 2,639
  • 1
  • 20
  • 36
1

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!

Neil
  • 5,762
  • 24
  • 36
1

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;
  }

  // ...
}
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
1

If name is present as String, simply do this,

int getId(String name){
  EnumCountry country = EnumCountry.valueOf(name);
  return country.getId();
}
Amber Beriwal
  • 1,568
  • 16
  • 30