Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Array List of Objects based on a variable in object

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.

like image 708
Hypergiant Avatar asked May 11 '12 04:05

Hypergiant


People also ask

How do you sort a list of objects based on an attribute of the objects in Java 8?

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.

How do you sort an array of objects based on a property in Java?

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.

How do you sort a list containing objects?

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.


1 Answers

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.

like image 62
Alex Lockwood Avatar answered Sep 22 '22 06:09

Alex Lockwood