I have an ENUM with only 3 constant. Based on flag, named weekend, ENUM.values() should return either 3 or 2 constants.
public enum Weekday {
SUNDAY, MONDAY, TUESDAY;
}
public Weekday[] getDays() {
boolean weekend = true;
if (weekend){
return Weekday.values() // this will reurn SUNDAY, MONDAY, TUESDAY
} else { // when weekend is false
return Weekday.values() // it should return on MONDAY, TUESDAY
}
}
Please suggest, what is the a reasonable good approach to achieve this. I am able to achieve it with the below code. Unfortunately, the PR reviewer does not seem to be happy this that. Could you suggest a better approach?
My solution.
EnumMap<Weekday, Integer> days= new EnumMap<>(Weekday.class);
days.put(Weekday.MONDAY, 1);
days.put(Weekday.TUESDAY, 2);
return days.keySet().toArray(new Weekday[0]); // this returns MONDAY and TUESDAY.
Advertisement
Answer
How about:
public enum Weekday {
SUNDAY, MONDAY, TUESDAY;
}
public Weekday[] getDays() {
boolean weekend = callFromSomeAPI();
return weekend ? Weekday.values() : new Weekday[] {Weekday.MONDAY, Weekday.TUESDAY};
}
Of course, in a more typical use of the Enum Weekday would be to represent all the 7 days of the week, and using a variable (e.g., weekend or weekdays) to differentiate from week days and weekend days. Something like:
enum Weekday {
MONDAY(false),
TUESDAY(false),
WEDNESDAY(false),
THURSDAY(false),
FRIDAY(false),
SATURDAY(true),
SUNDAY(true);
private final boolean weekend;
Weekday(boolean weekend) {
this.weekend = weekend;
}
public static Weekday[] getDays(boolean weekend) {
return Arrays.stream(values()).filter(i -> i.weekend == weekend).toArray(Weekday[]::new);
}
}