查找String是否不在ENUM列表中的最佳方法

Ang*_*ina 6 java enums

我需要查找给定的String是否不在的列表中ENUMs

这些Strings带有空格,例如:“儿童护理”,“信用卡”等。

除以外的任何其他ExpenseType映射都应映射到。应该完全忽略。OTHERHOAHOA

我的ENUM如下:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在这样做的方式如下:

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());
}
Run Code Online (Sandbox Code Playgroud)

有人知道更好的方法吗?

use*_*900 4

如果适用,为什么不使用getEnum来获取 Enum(如果需要,检查 null 或使用Optional)

ExpenseType monthlyExpenses = EnumUtils.getEnum(ExpenseType.class, expenseDescription);
Run Code Online (Sandbox Code Playgroud)

获取类的枚举,如果未找到则返回 null。

此方法与 Enum.valueOf(java.lang.Class, java.lang.String) 的不同之处在于,它不会针对无效的枚举名称引发异常。

还喜欢向枚举添加代码(字符串)作为引用,该代码不包含空格和特殊字符,例如

//...
CHILDCARE("CHILD_CARE","CHILD CARE"),
//...
private String expenseType; 
private String expenseTypeCode; 
ExpenseType(String expenseType, String expenseTypeCode) {
    this.expenseType = expenseType;
    this.expenseTypeCode = expenseTypeCode;
}   
Run Code Online (Sandbox Code Playgroud)