Activity Forums Salesforce® Discussions How can I Sort Wrapper list in Salesforce?

  • Mohit

    September 16, 2016 at 6:45 am

    Hi Pranav,

    Here is the code for sorting the wrapper list:-

    global class Book implements Comparable {

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

    public enum SORT_BY {

    //Variable to decide the member on which sorting should be performed
    public static SORT_BY sortBy = SORT_BY.ByTitle;

    public Book(String bt, String a, Integer tp, Double p, Date pd)
    BookTitle = bt;
    Author = a;
    TotalPages = tp;
    Price = p;
    publishingDate = pd;

    global Integer compareTo(Object objToCompare) {
    //Sort by BookName Alphabetically
    if(sortBy == SORT_BY.ByTitle)
    return BookTitle.compareTo(((Book)objToCompare).BookTitle);
    else //Sort by Book price
    return Integer.valueOf(Price - ((Book)objToCompare).Price);

  • shariq

    September 19, 2018 at 1:13 pm


    You can use the sort() method of Salesforce List class.

    sort() :
    Sorts the items in the list in ascending order.


  • Parul

    September 22, 2018 at 5:25 am

    Adding some points and code snippet:

    37down vote
    Apex provides a sort method on the List class for sorting. For objects such as this however, you must implement the Comparable interface. Note the Salesforce doc samples indicate you need to make your class 'global' scope, this is no longer true.

    public class jobsWrapper implements Comparable
    public Integer compareTo(Object compareTo)
    jobsWrapper jobsWrapper = (jobsWrapper) compareTo;
    if (job.Name == jobsWrapper.job.Name) return 0;
    if (job.Name > jobsWrapper.job.Name) return 1;
    return -1;
    Then once you put your objects into a list you can use the sort method.

    List<jobsWrapper> jobs = new List<jobsWrapper>();
    // Add things to the list ...



Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos