Skip to content
Advertisement

How can i can get Strings from Enum after using toString()

I am creating a list from which the user can select from using Vaadin8. I want to get the values from the Enum but the string values with spaces not the Element Names.

public enum CustomerStatus {
    
    ImportedLead {
        public String toString() {
            return "Imported Lead";
        }
    }, 
     NotContacted{
        public String toString() {
            return "Not Contacted";
        }
    }, 
     Contacted{
        public String toString() {
            return "Contacted";
        }
    }, 
     Customer{
        public String toString() {
            return "Customer";
        }
    }, 
     ClosedLost{
        public String toString() {
            return "Closed Lost";
        }
    }
}

Here is the list created to select from the Enum elements:

private NativeSelect <CustomerStatus> status = new NativeSelect<>("Status");

And here are 3 lines I tried that did not work:

status.setItems(CustomerStatus.values().toString());

//
status.setItems(CustomerStatus.valueOf(CustomerStatus.values())); 
//
status.setItems(CustomerStatus.ClosedLost.toString(), CustomerStatus.Contacted.toString() , CustomerStatus.Customer, CustomerStatus.NotContacted, CustomerStatus.ImportedLead);
//

Answer

You can add a value property:

  public enum CustomerStatus {

  ImportedLead("Imported Lead"),
  NotContacted("Not Contacted"),
  Contacted("Contacted"),
  Customer("Customer"),
  ClosedLost("Closed Lost");

  private final String value;

  CustomerStatus(String value) {
    this.value = value;
  }

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

  public static CustomerStatus fromValue(String value) {
    CustomerStatus result = null;
    switch(value) {
      case "Imported Lead":
      result = CustomerStatus.ImportedLead;
      break;
      case "Not Contacted":
      result = CustomerStatus.NotContacted;
      break;
      case "Contacted":
      result = CustomerStatus.Contacted;
      break;
      case "Customer":
      result = CustomerStatus.Customer;
      break;
      case "Closed Lost":
      result = CustomerStatus.ClosedLost;
      break;
    }
    if (result == null) {
      throw new IllegalArgumentException("Provided value is not valid!");
    }
    return result;
  }
}

Usage:

status.setItems(Arrays.asList(CustomerStatus.values()));
Advertisement