There is a standard way of sorting, for instance if a list of account is being sorted and the account contains name field in the list the ...
Skiptocontent
Standardsortingmethod
ThesortmethodoflistclassprovidessortingforsObject typelist.Thereisastandardwayofsorting,forinstanceifalistofaccountisbeingsortedandtheaccountcontainsnamefieldinthelistthesortingwillbebasedonnamefield,andiftwoaccounts’nameisfoundsamenextfieldinalphabeticorderwillbeusedtosort.ClickStandardSortingonsObjectList.
Aclient’s requirementmademedocustomsortingofsObjectList.Wecan’tsortthelistofopportunitybasedonamountfieldusingsortmethodprovidedbylistclassbutwecancustomizethesortingbehavior.WeneedtocreateawrapperclassfortheopportunitysObjecttosortitbasedonAmount.
globalclassOpportunityWrapperimplementsComparable{
publicOpportunityoppy;
//Constructor
publicOpportunityWrapper(Opportunityop){
oppy=op;
}
//Compareopportunitiesbasedontheopportunityamount.
globalIntegercompareTo(ObjectcompareTo){
//CastargumenttoOpportunityWrapper
OpportunityWrappercompareToOppy=(OpportunityWrapper)compareTo;
//Thereturnvalueof0indicatesthatbothelementsareequal.
IntegerreturnValue=0;
if(oppy.Amount>compareToOppy.oppy.Amount){
//Setreturnvaluetoapositivevalue.
returnValue=1;
}elseif(oppy.Amount(decimal)SecondValue)||
(SortOrder=='DESC'&&(Decimal)firstValue((Decimal)SecondValue))||
(SortOrder=='ASC'&&((Decimal)firstValue)compareToDate)||
(SortOrder=='DESC'&¤tcompareToDate)||
(SortOrder=='ASC'&¤tclassMap;
PublicStringfieldtype;
PublicCustomClassSorter(Sortableob,Stringsf,Stringsorder,StringFieldType){
so=ob;
sortfield=sf;
SortOrder=sorder;
classMap=(Map)JSON.deserializeUntyped(JSON.serialize(ob));
this.FieldType=FieldType;
}
publicIntegercompareTo(ObjectcompareTo){
CustomClassSortercompareToOppy=(CustomClassSorter)compareTo;
Sortablesocopy=compareToOppy.so;
MapclassMapToCompare=(Map)JSON.deserializeUntyped(JSON.serialize(socopy));
ReturnsorterHelper.sortRecord(SortOrder,fieldtype,classMap.get(sortfield),classMapToCompare.get(sortfield));
}
}
ListSortingforRelationalFieldsObject
TheRelationshipfieldbasedsortingshouldbemanuallymodifiedaspertherequirement,belowclassIhaveimplementedthecodetosortalistofcontactbasedonAccount’sName.Wecan’tgetAccount.namefromasObjectvariable,soneedtomodifythecodeforeachfieldandsObjectwewant.
IhavecreatedanewClassandInheritedthesObjectSortersothatIdon’thavetochangethecodealreadywritten.
publicclasssObjectRelationalSorterextendssObjectSorter{
PublicsObjectsobj;
PublicStringsortfield;
PublicStringsortOrder;
PublicsObjectRelationalSorter(){}
PublicsObjectRelationalSorter(sObjectsb,Stringsorder,Stringsortfield){
sobj=sb;
SortOrder=sorder;
this.sortfield=sortfield;
}
publicoverrideIntegercompareTo(ObjectcompareTo){
sObjectRelationalSortercTo=(sObjectRelationalSorter)compareTo;
SobjectcompareToOppy=cTo.sobj;
IntegerreturnValue=0;
StringsObjType=String.valueof(sobj.getSObjectType());
//parsethesobjecttoexactsObjectandusethelogicgivenbelowandaddcases
//Anexampleforrelationshipfieldbasedsorting
if(sObjType=='Contact'&&sortfield.tolowercase()=='account.name'){
Contactcurrent=(Contact)sobj;
ContactcontactcomparedTo=(Contact)compareToOppy;
if((SortOrder=='ASC'&¤t.Account.name>contactcomparedTo.account.name)||
(SortOrder=='DESC'&¤t.Account.namecontactcomparedTo.account.name)||(SortOrder=='ASC'&¤t.Account.nametheList=newList();
for(sObjects:records){
sObjectSorterv;
if(!fieldname.contains('.')){
v=newsObjectSorter(s,fieldname,SortOrder);
theList.add(v);
}else{
v=NewsObjectRelationalSorter(s,SortOrder,fieldname);//fieldnameshouldbehardcoded
theList.add(v);
}
}
theList.sort();
records.clear();
for(sObjectSortercs:theList){
if(!fieldname.contains('.'))
records.add(cs.sobj);
else{
sObjectRelationalSorterrs=(sObjectRelationalSorter)cs;
records.add(rs.sobj);
}
}
}
Examples
Exampleforcustomclass
Sorter.sort(thelist,'dtm','ASC','datetime');
Sorter.sort(thelist,'dtm','DESC','datetime');
ExampleforSobjectList
Public sObjectSortctr (){
List conlist=[select id,Name,account.name,Birthdate from contact where Birthdate !=null];
Sorter.Sort(conlist,'Birthdate','ASC');
listfirst =new List();
listfirst.addall(conlist);
Sorter.Sort(conlist,'Birthdate','DESC');
listsecond =new List();
listsecond.addAll(conlist);
ExampleforparentsfieldsObject
List conlist=[select id,Name,account.name from contact where account.name !=null];
Sorter.Sort(conlist,'account.name','ASC');
listfirst =new List();
listfirst.addall(conlist);
Sorter.Sort(conlist,'account.name','DESC');
listsecond =new List();
listsecond.addAll(conlist);
Sharethis:TwitterFacebookLikethis:LikeLoading...
PublishedbyGauravSingh
ExperiencedSalesforceDeveloper.
Eagertohelpothers.
ViewallpostsbyGauravSingh
Postnavigation
PreviousPostNamingConventionsIn Apex
LeaveaReplyCancelreply
Enteryourcommenthere...
Fillinyourdetailsbeloworclickanicontologin:
Email(required)(Addressnevermadepublic)
Name(required)
Website
YouarecommentingusingyourWordPress.comaccount.
( Log Out /
Change )
YouarecommentingusingyourGoogleaccount.
( Log Out /
Change )
YouarecommentingusingyourTwitteraccount.
( Log Out /
Change )
YouarecommentingusingyourFacebookaccount.
( Log Out /
Change )
Cancel
Connectingto%s
Notifymeofnewcommentsviaemail.Notifymeofnewpostsviaemail.
Δ
LatestTopics
Listsortingin apex
NamingConventionsIn Apex
Search
Searchfor:
Privacy&Cookies:Thissiteusescookies.Bycontinuingtousethiswebsite,youagreetotheiruse.
Tofindoutmore,includinghowtocontrolcookies,seehere:
CookiePolicy
Follow
Following
SalesForceByGvs
Signmeup
AlreadyhaveaWordPress.comaccount?Loginnow.
SalesForceByGvs
Customize
Follow
Following
Signup
Login
Copyshortlink
Reportthiscontent
ViewpostinReader
Managesubscriptions
Collapsethisbar
LoadingComments...
WriteaComment...
Email(Required)
Name(Required)
Website
%dbloggerslikethis: