-2

I have the following enum that contains two values, a string identifier and a boolean valid status. I would like to be able to get the status value by using the string identifier.

Has anyone got any suggestions what I can add to the code below?

public enum MyEnum {

    TYPEA("001", true),
    TYPEB("002", false);
    
    private final String identifier;
    private final boolean valid;

    MyEnum(String identifier, boolean valid) {
        this.identifier = identifier;
        this.valid = valid;
    }
}
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
user2254180
  • 844
  • 13
  • 30
  • 4
    Does this answer your question? [How to get the enum type by its attribute?](https://stackoverflow.com/questions/7888560/how-to-get-the-enum-type-by-its-attribute) – kasptom Dec 09 '20 at 16:20
  • 1
    No, I am trying to get an enum value by another enum value. – user2254180 Dec 09 '20 at 16:21

2 Answers2

2

The ENUM types has the method values, which you can use to extract all the enum values and compare their identifier against the one that you have passed by the method parameter, namely:

public MyEnum getEnum(String identifier){
      for(MyEnum e : MyEnum.values())
         if(e.identifier.equals(identifier))
            return e;
      return null;
 }

or even better:

public static Optional<MyEnum> getEnum(String identifier){
        return Arrays.stream(MyEnum.values()).filter(i -> i.identifier.equals(identifier)).findFirst();
}

This way you make it clear on the method signature that you might or not find the enum.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
1
public enum MyEnum {

   TYPEA("001", true),
   TYPEB("002", false);

   private final String identifier;
   private final boolean valid;

   MyEnum(String identifier, boolean valid) {
       this.identifier = identifier;
       this.valid = valid;
   }

   public static MyEnum getFromIdentifier(String identifier) {
       return Arrays.stream(MyEnum.values()).filter(item -> item.identifier.equals(identifier)).findFirst().orElse(null);
   }
}
Fabien MIFSUD
  • 335
  • 5
  • 14