Created
January 24, 2019 13:04
-
-
Save yasarshaikh/7c5b393cd660c82a9bfd8592888aa099 to your computer and use it in GitHub Desktop.
Custom Sort - Apex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************************** | |
Class : ComparableDemo | |
Purpose: To sort by custom field/variable in Wrapper class, in following case- CreatedDate | |
Example: //Sample Apex code be executed in Anonymous window | |
List<ComparableDemo> lCD = new List<ComparableDemo>(); | |
List<Account> lAcct = [select id, createdDate from Account order by lastModifiedDate desc]; | |
for(Account a: lAcct) | |
{ | |
lCD.add(new ComparableDemo(a)); | |
} | |
lCD.sort(); | |
for(ComparableDemo oC:lCD) | |
System.debug(oC.acct.ID + ' || ' + oC.acct.CreatedDate); | |
****************************************************************/ | |
public class ComparableDemo implements Comparable | |
{ | |
public Account acct; | |
public ComparableDemo(Account a){ | |
this.acct =a; | |
} | |
public Integer compareTo(Object compareTo) { | |
ComparableDemo cd = (ComparableDemo)compareTo; | |
Account compareToAcct = cd.acct; | |
//If both are equal | |
if(compareToAcct.get('CreatedDate') == acct.get('CreatedDate')) return 0; | |
//IF:my current account i.e. the one declared above is small, then return -1(so that it will be ascending) | |
if(compareToAcct.CreatedDate > acct.CreatedDate) return -1; | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment