Are you looking for a way to sort a list of weekdays in Java?
In this article, I will show you how you can achieve that using Stream, Enum and DayOfWeek java time api.
Sorting with Enum
One way to sort unordered days of the week list is using Enumeration.
In fact, the order of an instance of Enum is returned via the ordinal() function. This instance method reflects the order in the Enum declaration in which the starting constant is given the ordinal 0 in the Enum declaration. This concept is similar to array indexes.
So letβs declare our enumeration.
public enum WeekDay {
MONDAY("MONDAY"),
TUESDAY("TUESDAY"),
WEDNESDAY("WEDNESDAY"),
THURSDAY("THURSDAY"),
FRIDAY("FRIDAY"),
SATURDAY("SATURDAY"),
SUNDAY("SUNDAY");
private final String value;
WeekDay(String value) {
this.value = value;
}
public static WeekDay fromValue(String value) {
for (WeekDay day : WeekDay.values()) {
if (day.value.equals(value.toUpperCase())) return day;
}
throw new IllegalArgumentException("Unexpected Value β " + value);
}
}
Now consider a method that returns an unordered list of days of the week, maybe taking from a database query.
public static List<String> getWeekDays() {
return new ArrayList<>(
Arrays.asList("Thursday", "Saturday", "Monday", "Friday", "Tuesday", "Sunday", "Wednesday")
);
}
This is how you could sort it.
getWeekDays().stream()
.map(WeekDay::fromValue)
.sorted()
.map(WeekDay::toString)
.collect(Collectors.toList());
Output
> [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
Sorting with DayOfWeek Class
Another way of sorting day of the week is by using DayOfWeek
java.time class. With the previous example, we can have the following
import java.time.DayOfWeek;
//...
//...
getWeekDays().stream()
.map(day -> DayOfWeek.valueOf(day.toUpperCase()))
.sorted()
.map(String::valueOf)
.collect(Collectors.toList());
Output
> [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
Any way, if you want to get the result in the opposite order, you can use java.util.Comparator
.
//...
getWeekDays().stream()
.map(day -> DayOfWeek.valueOf(day.toUpperCase()))
.sorted(Comparator.reverseOrder())
.map(String::valueOf)
.collect(Collectors.toList());
//...
This will then be the output
> [SUNDAY, SATURDAY, FRIDAY, THURSDAY, WEDNESDAY, TUESDAY, MONDAY]
π. Similar posts
React Component Cleanup
12 Mar 2025
How to Run Code on Mount in Your React Components Easily
04 Mar 2025
Best Practices for Using the useEffect Hook in React
22 Feb 2025