I have an Array List of Objects
The objects in the Array List are information for college called 'ModuleInfo' (course, assignments, dateDue)
The dateDue has been formatted into an integer YYYYMMDD (From a calendar)
I've looked at some of the other ways people have done this, but I can't get my head around what it is that I need to do.
Ideally because I've already stated when creating the Array List that it will contain 'ModuleInfo' objects I could just Collection.sort(moduleDB, ModuleInfo.getDateDue) or something along those lines. moduleDB being the Array List
Any help would be much appreciated.
Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.
To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see the new Fruit class again. The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.
sort() method to sort a list of objects using some examples. By default, the sort() method sorts a given list into ascending order (or natural order). We can use Collections. reverseOrder() method, which returns a Comparator, for reverse sorting.
If you want to use Collections.sort(List list)
to sort your list, your object must implement the Comparable
interface.
public class ModuleInfo implements Comparable<ModuleInfo> {
/* Your implementation */
public int compareTo(ModuleInfo info) {
if (this.dateDue < info.dateDue) {
return -1;
} else if (this.dateDue > info.dateDue) {
return 1;
} else {
return 0;
}
}
}
Then call Collections.sort(moduleDB)
where moduleDB
has type ArrayList<ModuleInfo>
.
p.s. As mentioned in a previous post, you can also have your class implement the Comparator
interface to achieve identical results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With