In this video we will see how to make an object comparable and sort array lists using the comparable and comparator interfaces.
To make an object comparable, we need to implement either the comparable interface and implement the compareTo method, or use the Comparator interface and implement its compare method.
In this video we work with in Item object, which we can sort it by id, price and object name.
You might need to sort an array lists in various cases, for example: to rearrange the order of a list that feeds your Recycler View component.
For the purpose of this tutorial we use Android Studio and Java as the programming language.
We define a class called Item and we define its properties and methods.
The Item class implements the Comparable interface.
As always, when implementing an interface we need to implement its methods.
The method that makes our class comparable is the “compareTo” method.
In the “compareTo” method we pass an object of type Item as a parameter and inside the method we compare the id of the object that implements the method with the id of the object sent as parameter.
The values returned are as follows:
- 1 – if the id of the object implementing the method is bigger than the id of the object passed as parameter
- -1 – if the id of the object passed as parameter is bigger than the id of the object which implements the method
- 0 – if the two id values of the two objects are equal.
To do the sorting, we call the Collections.sort method and then we pass the Item list as a parameter to the sort method. The second parameter defines the order in which the array list is sorted: ascending or descending.
In this tutorial I also show you how to implement the Comparator interface.
Whenever a class implements the Comparator interface, it needs to define the “compare” method.
In the defined Item class, we implement the compare method to be able to compare() two items by their price and by their name.
The “compare(Item item1, Item item2)” method receives two Item object as parameters and then it compares the corresponding values (whether we want to compare the Item prices or the Item names).
If you have any questions and comments, please leave them in the section below.
Thank you for visiting us!