byetisener
byetisener

Reputation: 310

How to solve unexpected behaviour of custom comparator while sorting a list of objects?

I am trying to sort a list of Objects (called Reminder) which are shown in a recyclerview in my Android app. I am using a custom comparator to compare one of the variables of the Object which is a type int.

I have managed to sort the list of objects by using another variable which is a date. The custom comparator I made works fine with Date objects.

This is the comparator I am using to sort Objects using the integer variable, which is the "priority" of the object in this case.

public void sortByPriority(){
        Collections.sort(reminderList, new Comparator<Reminder>() {
            @Override
            public int compare(Reminder o1, Reminder o2) {
                return o1.getPriority() - o2.getPriority();
            }
        });
        reminderAdapter.notifyDataSetChanged();
    }

There is a button on the layout that calls the sortByPriority() method above. When clicked it actually does some sorting operation, but the results are not consistent in the list or in the recyclerview.

For example, the initial data set is something like this (priority values range from 1 to 4 and priority belongs to the reminder class)

(Initial Data: 4,1,1,4,2,3,2,1,1,2)

(Sorted Using the above comparator: 1,1,1,2,2,4,1,2,3,4)

It looks like it is just about to work correctly but something happens in the middle. (I want them in descending order by the way)

I am fairly new so I may be messing up. Thank you very much for your help.

Upvotes: 0

Views: 68

Answers (1)

Binary Baba
Binary Baba

Reputation: 2083

The compare method basically tells that which of the passed parameter is greater.

In your example, if the function returns a positive number, it means o1 is greater, if 0 then it means they are equal. and if negative, then o2 is greater.

public int compare(Reminder o1, Reminder o2) {
 return o1.getPriority() - o2.getPriority();
}

If you want them in a descending order, you can do that in two ways. First is by reversing the compare method logic.

public int compare(Reminder o1, Reminder o2) {
 // o2 - o1 instead of o1 - o2
 return o2.getPriority() - o1.getPriority();
}

and another way is by using Collections.reverseOrder() after you have sorted the list.

Collections.sort(reminderList, Collections.reverseOrder());

and regarding the incorrect values, can you check your data once again with the consideration of above logic.

Upvotes: 1

Related Questions