I need to find if given String
is not in the list of ENUMs
.
These Strings
come back with spaces, i.e.: "CHILD CARE", "CREDIT CARDS", etc...
Any other ExpenseType
should be mapped to OTHER
, except HOA
. HOA
should be completely ignored.
My ENUMs are as follows:
public enum ExpenseType {
AUTOLOAN("AUTO LOAN"),
ALIMONY("ALIMONY"),
CHILDCARE("CHILD CARE"),
CREDITCARDS("CREDIT CARDS"),
INSTALLMENTLOANS("INSTALLMENT LOANS"),
FOOD("FOOD"),
UTILITIES("UTILITIES"),
TRANSPORTATION("TRANSPORTATION"),
OTHER("OTHER");
private String expenseType;
ExpenseType(String expenseType) {
this.expenseType = expenseType;
}
@Override public String toString() {
return this.expenseType;
}
}
The way I am doing this now is as follows:
String expenseDescription = expense.getExpenseDesc().replaceAll(" ", "");
if(EnumUtils.isValidEnum(ExpenseType.class, expenseDescription)) {
monthlyExpenses.setType(ExpenseType.valueOf(expenseDescription).toString());
}
else if(!expenseDescription.equals("HOA")) {
monthlyExpenses.setType(ExpenseType.OTHER.toString());
}
Does anyone know a better way to do this?
collect(Collectors. toList()). contains(aString); EventNames is the name of the enum while getEvent() is what returns the associated string value of each enum member.
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
For comparing String to Enum type you should convert enum to string and then compare them. For that you can use toString() method or name() method. toString()- Returns the name of this enum constant, as contained in the declaration.
Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .
Why not use getEnum to get Enum if applicable (check for null or use Optional if needed)
ExpenseType monthlyExpenses = EnumUtils.getEnum(ExpenseType.class, expenseDescription);
Gets the enum for the class, returning null if not found.
This method differs from Enum.valueOf(java.lang.Class, java.lang.String) in that it does not throw an exception for an invalid enum name.
Also prefer adding to enum a code (String) as a reference, which won't contains spaces and special characters, e.g.
//...
CHILDCARE("CHILD_CARE","CHILD CARE"),
//...
private String expenseType;
private String expenseTypeCode;
ExpenseType(String expenseType, String expenseTypeCode) {
this.expenseType = expenseType;
this.expenseTypeCode = expenseTypeCode;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With