Is there any existing library that I use to convert a list of days of weeks into a hyphenated/concatenated String?
For example:
["Monday", "Tuesday", "Wednesday", "Friday"]
would become "Monday - Wednesday, Friday"
The list will always contain unique days. So you'll never see ["Monday", "Monday", "Tuesday", ...]
.
Thanks!
SOLUTION
Thanks to kamoor1982's solution below
I had to make a few changes to his code to handle edge cases:
enum DayEnum {
Monday(1),
Tuesday(2),
Wednesday(3),
Thursday(4),
Friday(5),
Saturday(6),
Sunday(7);
private int value;
DayEnum(int x) {
this.value = x;
}
public int getValue() {
return value;
}
}
...
public static String concatenateDays(List<String> days) {
// Null check
if (days == null || days.isEmpty()) {
return "";
}
// Sort list according to order it appears in calendar with Monday as starting day
Collections.sort(days, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
DayEnum lhsEnum = DayEnum.valueOf(lhs);
DayEnum rhsEnum = DayEnum.valueOf(rhs);
return lhsEnum.compareTo(rhsEnum);
}
});
StringBuffer result = new StringBuffer(days.get(0));
DayEnum valueOf = DayEnum.valueOf(result.toString());
int previousIndex = valueOf.getValue();
int length = days.size();
for (int i = 1; i < days.size(); i++) {
String day = days.get(i);
if (previousIndex + 1 == DayEnum.valueOf(day).getValue()) {
if (i == length - 1 || DayEnum.valueOf(day).getValue() + 1 != DayEnum.valueOf(days.get(i + 1)).getValue()) {
result.append(" - ");
result.append(day);
}
} else {
result.append(", ");
result.append(day);
}
previousIndex = DayEnum.valueOf(day).getValue();
}
return result.toString();
}