Use ENUM to default value to ineligible

Angelina :

I have following code that handles EligibilityType:

public enum EligibilityType {

    E (EligibilityTypeEnum.ELIGIBLE),
    I (EligibilityTypeEnum.INELIGIBLE);

    private final EligibilityTypeEnum eligibilityTypeEnum;

    private EligibilityType(EligibilityTypeEnum eligibilityTypeEnum) {
        this.eligibilityTypeEnum = eligibilityTypeEnum;
    }

    public EligibilityTypeEnum toEligibilityTypeEnum() {
        return eligibilityTypeEnum;
    }
}

I learned that everything that is not of value "E" should be set to EligibilityTypeEnum.INELIGIBLE.

And this is how I am calling it:

...
List<Workout> workouts = workoutResults.getWorkout();
for(int i = 0; i< workouts.size(); ++i) {
    ...
    stin.getWorkouts().get(i).setEligibilityType(EligibilityType.valueOf(workouts.get(i).getRecommendation()).toEligibilityTypeEnum());
    ...
}

Right now the code blows up if workouts.get(i).getRecommendation() returns "C".

Does anyone see any other way of achieving this except try-catch?

Is there a way to set a default value in enum?

Adrian :

you can have in EligibilityType a map with all possible values

public static final Map<String, EligibilityType> ALL_MAP = Arrays.stream(values())
            .collect(Collectors.toMap(Enum::toString, Function.identity()));

then you can handle gracefully the default case

EligibilityType.ALL_MAP.getOrDefault(someString, EligibilityType.DEFAULT)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134591&siteId=1