0

I have the following enum, it contains label and field values. I would like to return the field by passing in the label name.

Can anyone make any suggestions?

public enum Table (
   NAME("name", "FULL_NAME");

   public final String label;
   public final String field;

   private Table(String label, String field) {
   this.label = label;
   this.field = field;
   }
}
1
  • 1
    It's actually trivial, add a static method public static String fieldByLable(String label) { String result = null; for(Table i: Table.values()) { if( i.lable.equals(label) ) { result = i.field; break;} } retrurn result; } and then simply String value = Table.fieldByLable("name"); In any case, you need Map forget about enum, for this scenario. Commented Mar 11, 2020 at 17:20

1 Answer 1

2

Add method getField to your enum

public enum Table (
   NAME("name", "FULL_NAME");

   public final String label;
   public final String field;

   private Table(String label, String field) {
   this.label = label;
   this.field = field;
   }

   public static String getField(String label) {
     String result = null;
     for(Table t : Table.values()) {
       if(t.label.equals(label) {
         result = t.field;
         break;
       }
     }
     return result;
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

You need to return result

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.