• #15944
    Salesforce | PRANAV PRANAV #682

    How can I Sort Wrapper list in Salesforce?

    Hi All,

    How can I Sort Wrapper list?

    I have made a wrapper class in which there is a list of searched products, I want to display those searched result in ascending order of their name.



    Salesforce | Mohit Mohit #498

    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);

    Salesforce | shariq shariq #1


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

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


    Salesforce | Parul Parul #2

    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 …



Viewing 4 posts - 1 through 4 (of 4 total)

Please to reply to this topic.


We're not around right now. But you can send us an email and we'll get back to you, asap.


About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2019 Forcetalks. All Right Reserved.

Log in with your credentials


Forgot your details?