Ken Reid
Ken Reid

Reputation: 609

Collections Sort Issue in Java

To put it simply, I have a list of weeks ArrayList<Week>, each of which contains a list of days ArrayList<Day>, each of which contains a Date object within the Day class. In other words, Weeks, have Days, have Dates.

For a problem I have to randomize the ArrayList<Week>, which I use Collections.shuffle for and works fine.

I then need to put them back in order, and I attempted this with:

public void sortWeeksInDateOrder(final List<Week> weeks) {
Collections.sort(weeks, new Comparator<Week>() {
        @Override
        public int compare(final Week week1, final Week week2) {
        //Return -1 or 1 if first date is before or after second date.
            return week1.getAllDays().get(0).getDate().before((week2.getAllDays().get(0).getDate())) ? -1 : 1;
        }
    });
}

However it's not sorting. Am I missing something? The weeks are never the same so I don't need to return a 0, so I thought this solution would work.

Upvotes: 0

Views: 64

Answers (1)

mlewandowski
mlewandowski

Reputation: 802

To make it clean, you should implement Comparable interface to Week class and provide implementation details to compareTo method saying how you want to compare Weeks.

Therefore, it would be enough to write:

Collections.sort(weeks, new Comparator<Week>() {
        @Override
        public int compare(final Week week1, final Week week2) {
            return week1.compareTo(week2);
        }
    });

Upvotes: 2

Related Questions