Sort Wrapper List by multiple values

Sample Apex Class:

public class Book implements Comparable {

    public String BookTitle ;
    public String Author;
    public Double Price ;
    public Date publishingDate;

    public Book(String bt, String a, Double p, Date pd) {
        BookTitle = bt;
        Author = a;
        Price = p;
        publishingDate = pd;
    }

    public Integer compareTo(Object objToCompare) {
        Book BooksWrapper = (Book)objToCompare;
        if ( this.BookTitle >  BooksWrapper.BookTitle) {
            return 1;
        } else if ( BookTitle < BooksWrapper.BookTitle ) {
            return -1;
        } else if ( Author < BooksWrapper.Author ) {
            return 1;
        } else if (Author > BooksWrapper.Author ) {
            return -1;
        }  else if ( Price < BooksWrapper.Price ) {
            return 1;
        } else if (Price > BooksWrapper.Price ) {
            return -1;
        } else {
            return 0;
        }
    }
    
}

In the above example, Books wrapper list is first ordered by BookTitle in ascending order and then ordered by Author and Price in descending order.

Execute the below code in Developer Console.

Book[] books = new Book[]{
new Book('Salesforce Developer Guide', 'Kanetkar',58, Date.newInstance(2016, 05, 20)),
new Book('Salesforce Developer Guide', 'Jeff Douglas', 35, Date.newInstance(2011, 08, 20)),
new Book('Salesforce Developer Guide', 'Yashavant P. Kanetkar', 58, Date.newInstance(2008, 02, 01)),
new Book('Handy Lightning Book','Elisabeth Freeman', 28,Date.newInstance(2018, 11,15)),
new Book('Salesforce Developer Guide', 'Kanetkar', 78, Date.newInstance(2008, 11, 29)),
new Book('First SOQL', 'Elisabeth Freeman', 28, Date.newInstance(2004, 10,21))
};

books.sort();

for ( Book b : books)
    system.debug(b);

Output:


Cheers!!!

No comments:

Post a Comment