Java – Custom sort the days of the week on the ArrayList

Custom sort the days of the week on the ArrayList… here is a solution to the problem.

Custom sort the days of the week on the ArrayList

I want to sort the list of string arrays so that all Mondays are at the beginning of the list and all Fridays are at the end. For example,

days.add("Thursday");
days.add("Monday");
days.add("Friday");
days.add("Wednesday");
days.add("Thursday");
days.add("Thursday");

I expect the output to be as follows;

"Monday"
"Wednesday"
"Thursday"
"Thursday"
"Thursday"
"Friday"

I

do this because I need to chart the results and I want the charts to be in that order. I was thinking maybe it would be possible to use the mapping to put Monday, 1:Tuesday, 2, etc. and compare that way, but I don’t know if there’s an easier way. Thank you very much for any help thank you!

Solution

You can use an enumeration for the days of the week because each enumeration has its own value underneath.

public enum DayOfTheWeek {
    Monday, //default value of 0
    Tuesday, //default value of 1
    Wednesday, //default value of 2
    Thursday, 
    Friday,
    Saturday,
    Sunday
}

Then simply make DayOfTheWeek’s ArrayList and use Collections.sort().

    ArrayList<DayOfTheWeek> days = new ArrayList<>();
    days.add(DayOfTheWeek.valueOf("Friday"));
    days.add(DayOfTheWeek.valueOf("Monday"));
    days.add(DayOfTheWeek.valueOf("Saturday"));
    days.add(DayOfTheWeek.valueOf("Sunday"));
    Collections.sort(days);

Related Problems and Solutions