Comparable: Sorting Objects in Salesforce - Biswajeet Samal

文章推薦指數: 80 %
投票人數:10人

The Comparable interface adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types. TheComparableinterfaceaddssortingsupportforListsthatcontainnon-primitivetypes,thatis,Listsofuser-definedtypes. ToaddListsortingsupportforyourApexclass,youmustimplementtheComparableinterfacewithitscompareTomethodinyourclass. WhenaclassimplementstheComparableinterfaceithastoimplementamethodcalledcompareTo().ThismethodreturnsanIntegervaluethatistheresultofthecomparison.Inthatmethodthecodehastobewrittentodecideiftwoobjectsmatchorifoneislargerthantheother. Theimplementationofthismethodshouldreturnthefollowingvalues: 0ifthisinstanceandobjectToCompareToareequal >0ifthisinstanceisgreaterthanobjectToCompareTo <0ifthisinstanceislessthanobjectToCompareTo Let’stakealookatasimpleclassthattakesinanEmployeeobject,storestheemployee’sdatainitandallowsustosortalistofEmployeesbytheirEmployeeId. ApexClass: publicclassEmployeeimplementsComparable{ publicIntegerId; publicStringName; publicDecimalSalary; publicEmployee(Integeri,Stringn,Decimals){ Id=i; Name=n; Salary=s; } publicIntegercompareTo(ObjectobjToCompare){ Employeeemp=(Employee)objToCompare; if(Id==emp.Id){ return0; } elseif(Id>emp.Id){ return1; } else{ return-1; } } } ExecutethebelowcodeinDeveloperConsole. ListempList=newList(); empList.add(newBiswajeet.Employee(104,'JohnDoe',5000.00)); empList.add(newBiswajeet.Employee(102,'JoeSmith',9000.00)); empList.add(newBiswajeet.Employee(103,'CaraghSmith',10000.00)); empList.add(newBiswajeet.Employee(101,'MarioRuiz',12000.00)); //SortusingthecustomcompareTo()method empList.sort(); //Writelistcontentstothedebuglog for(Employeee:empList){ system.debug(e); } Output: Postnavigation ←ISBLANKandISNULLwithaRichTextFieldisnotworkinginValidationRule InstalltheForce.comIDEPlug-InForEclipse→ Search GetInTouch        TrailblazerCommunityProfileTechnologies .Net(7) ComputerTips&Tricks(2) Eclipse(2) HTML(6) JavaScript(26) MSSQLServer(9) PHP(1) Salesforce(714) ‎jQuery(2) Tags.Net Apex ApexClass ApexTrigger API ApprovalProcess Attachment BatchApex BatchClass C# DataTable Date Force.com FormulaField Javascript Json Lightning LightningComponent LightningDataService LightningFramework LightningOut LightningWebComponent List LWC MSSQLServer Object Pagination Picklist ProcessBuilder Profile QuickAction RecordType RESTAPI Salesforce Salesforce.com SFDC sObject SOQL SQLServerTips&Tricks StandardController TestClass Trigger User ValidationRule VisualforcePage SalesforceBlogsMember10MostPopularSalesforceDeveloperBlogsTop50SalesforceDeveloperBlogsVisitorsBiswajeetSamalBiswajeetSamalRecentTweetsTweetsby@itzbiswajeet Thiswebsiteusescookiestoimproveyourexperience.We'llassumeyou'reokwiththis,butyoucanopt-outifyouwish.AcceptReject



請為這篇文章評分?