ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

Sorting of sObjects in Salesforce

Home / Article & Blogs / Apex / Sorting of sObjects in Salesforce
By Subrat inApex

I had a requirement where I had to sort a list of custom object records (Product__c) by a custom text field Group__c alphabetically and then by a currency field Price__c from lowest to highest.

There is an instance method sort() for List collection type, it sorts the items in the list in ascending order. Using this method, we can sort primitive types, SelectOption elements and sObjects. But, I found out, Apex does not allow us to use this built-in method to sort a list of sObjects by any specific field of our choice.

If we write sort() method on a list of sObjects, then Salesforce uses a predefined sequence of comparison steps. These are as follows:

  1. The label of sObject type.
    Example:
    [sourcecode language=”java”]List<SObject> objs = new List<SObject>();Opportunity o1 = new Opportunity(Name=’opp1′);Contact c1 = new Contact(LastName = ‘con4’);

    objs.add(o1);

    objs.add(c1);

    objs.sort();

    for(SObject obj : objs){

    system.debug(obj);

    }

    Result :

    Contact:{LastName=con4}

    Opportunity:{Name=opp1}[/sourcecode]
    Contact record appears in list before an Opportunity even though it was added later.

  2. The name field, if present.
    [sourcecode language=”java”]List<SObject> objs = new List<SObject>();Opportunity o1 = new Opportunity(Name=’opp1′);Opportunity o2 = new Opportunity(Name=’opp2′);

    Opportunity o3 = new Opportunity(Name=’opp3′);

    objs.add(o3);

    objs.add(o2);

    objs.add(o1);

    objs.sort();

    for(SObject obj : objs){

    system.debug(obj);

    }

    Result:

    Opportunity:{Name=opp1}

    Opportunity:{Name=opp2}

    Opportunity:{Name=opp3}[/sourcecode]
    Opportunities are sorted by Name, ‘opp1’ comes first even though it was entered last.

  3. Standard fields, in alphabetical order (except Id and Name fields)
    [sourcecode language=”java”]List<SObject> objs = new List<SObject>();Opportunity o1 = new Opportunity(Name=’opp1′,Amount=300, StageName = ‘Qualification’);Opportunity o2 = new Opportunity(Name=’opp1′,Amount=300, StageName = ‘Prospecting’);

    Opportunity o3 = new Opportunity(Name=’opp1′,Amount=200, StageName = ‘Value Proposition’);

    objs.add(o1);

    objs.add(o2);

    objs.add(o3);

    objs.sort();

    for(SObject obj : objs){

    system.debug(obj);

    }

    Result:

    Opportunity:{Name=opp1, Amount=200, StageName=Value Proposition}

    Opportunity:{Name=opp1, Amount=300, StageName=Prospecting}

    Opportunity:{Name=opp1, Amount=300, StageName=Qualification}[/sourcecode]
    All the opportunities have same name, so these are sorted by Amount then and followed by StageName, record with ‘Prospecting’ appears before ‘Qualification’ even though added to the list later.

  4. Custom fields, in alphabetical order
Note:

Empty/blank fields appear before non-empty fields in sort order.

So, the question was, ‘How to achieve the functionality’.

Salesforce provides an interface called Comparable that can be used for sorting of custom class/wrapper class. The wrapper class needs to implement the Comparable interface and should contain a method named ‘compareTo’.

CompareTo method:

The syntax for this special method is –

public/global Integer compareTo(Object obj) {

//code to compare the values

}

Values returned:

positive value (usually 1 is used) – current value greater than compared value

negative value (usually -1 is used) – current value lesser than compared value

0 – current value and compared value are equal

Example:
[sourcecode language=”java”]

Public Class ProductWrapper implements Comparable{

Public Product__c product;

//constructor

Public ProductWrapper(Product__c prod){

this.product = prod;

}

public Integer compareTo(Object obj){

ProductWrapper wrapProduct = (ProductWrapper) obj;

If(product.Group__c > wrapProduct.Group__c)

return 1;

else if(product.Group__c < wrapProduct.Group__c)

return -1;

else {

if(product.Price__c > wrapProduct.Price__c)

return 1;

else if(product.Price__c < wrapProduct.Price__c)

return -1;

else

return 0;

}

}

}[/sourcecode]

Explanation:

These are the records available on Product__c object.

If I use the above custom sort with wrapper class I get the below result first order by Group alphabetically, then by Price lowest to highest.

A question for you, if I have to order the result by Group alphabetically then by Price from highest to lowest, how could I achieve this?

Simple, all I had to do is to return -1 when current price is greater than compared price.
[sourcecode language=”java”]

if(product.Price__c > wrapProduct.Price__c)

return -1;

else if(product.Price__c < wrapProduct.Price__c)

return 1;

else

return 0;[/sourcecode]

You can use the below snippet to run in developer console and see the result.
[sourcecode language=”java”]

public Class ProductWrapper implements Comparable{

Public Product__c product;

Public ProductWrapper(Product__c prod){

this.product = prod;

}

public Integer compareTo(Object obj){

ProductWrapper wrapProduct = (ProductWrapper) obj;

if(product.Group__c > wrapProduct.product.Group__c)

return 1;

else if(product.Group__c < wrapProduct.product.Group__c)

return -1;

else {

if(product.Price__c > wrapProduct.product.Price__c)

return -1;

else if(product.Price__c < wrapProduct.product.Price__c)

return 1;

else

return 0;

}

}

}

List<ProductWrapper> pList = new List<ProductWrapper>();

for(Product__c p : [ SELECT Name, Group__c, Price__c FROM Product__c]) {

pList.add(new ProductWrapper(p));

}

pList.sort();

for(ProductWrapper p : pList){

system.debug(p);

}[/sourcecode]

ComparableListSalesforceSort
140
Like this post
2 Posts
Subrat

Search Posts

Archives

Categories

Recent posts

BioAsia 2023 in Hyderabad: An Annual International Event

BioAsia 2023 in Hyderabad: An Annual International Event

The Role Of Marketing in Small & Medium Enterprises

The Role Of Marketing in Small & Medium Enterprises

Salesforce For Retail: How Salesforce CRM Can Help Retailers

Salesforce For Retail: How Salesforce CRM Can Help Retailers

What is ChatGPT & How Does It Work?

What is ChatGPT & How Does It Work?

What Is Graphic Design? (Executive Summary 2023)

What Is Graphic Design? (Executive Summary 2023)

  • Previous PostProcess automation with the help of visual workflows
  • Next PostCreating Google Calendar Events from Salesforce Without Integration

Related Posts

Integrate SharePoint with Salesforce using Microsoft Graph API
Apex Integration Salesforce

Integrate SharePoint with Salesforce using Microsoft Graph API

Cyber-security in an uncertain world
Apex

Cyber-security in an uncertain world

REST API call from Einstein Analytics Dashboard
Apex REST Salesforce Salesforce Einstein Wave Analytics

REST API call from Einstein Analytics Dashboard

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT