How to Sort Wrapper class Collection in Apex - Jitendra Zaa

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

How to Sort Wrapper class Collection in Apex · Comparable Interface: To implement the Comparable Interface, you must declare global class with ... Skiptocontent ThereisinbuiltfunctionalityinApextosorttheprimitivedatatypessupportedbyforce.com.Iamsuremaximumofdevelopersmusthavecomeacrossthesituationswheretheyneedtosortcustomdatatypebuiltbythemi.e.customclassorIwouldsaywrapperclassintermsofforce.com. Butthink,Howforce.comwillcometoknowthathowtosortclass?Incaseofinteger,dateordoubletheyalreadyknow.Buthowtheyaregoingtoknowthatwhatisgoingtobecontentinyourclass?BeforeSummer’12therewasnodirectway.HoweverthankstoSalesforcetointroducetheinterfaceComparableinSummer’12release.And…thereissmileonthefaceofJavadevelopers,becausetheyalreadyknowwhatitis. Solet’sstartwith“WhatistheuseofinterfaceComparable?“Iwouldsay,thisisthewaytotellforce.comthathowwearegoingtocomparethecustomObjects(Wrapperclass). ComparableInterface: ToimplementtheComparableInterface,youmustdeclareglobalclasswiththeimplementskeywordasfollow: globalclassBookimplementsComparable Now,yourclassmustimplementthemethod“compareTo“asfollow: globalIntegercompareTo(ObjectobjToCompare) { //Yourcodetoimplementlogic } compareTo()method: ThecompareTo()methodmustreturnfollowingintegervalue 0ifbothobjectisequal >0iftheinstanceobjectisgreaterthan“objToCompare” <0iftheinstanceobjectissmallerthan“objToCompare” Samplecode Let’staketheexampleofclass“Book”,whichhavefollowingdatamembers, BookTitle–String Author–String TotalPages–Integer Price–Double globalclassBookimplementsComparable{ publicStringBookTitle; publicStringAuthor; publicIntegerTotalPages; publicDoublePrice; publicDatepublishingDate; publicenumSORT_BY{ ByTitle,ByPage } //Variabletodecidethememberonwhichsortingshouldbeperformed publicstaticSORT_BYsortBy=SORT_BY.ByTitle; publicBook(Stringbt,Stringa,Integertp,Doublep,Datepd) { BookTitle=bt; Author=a; TotalPages=tp; Price=p; publishingDate=pd; } globalIntegercompareTo(ObjectobjToCompare){ //SortbyBookNameAlphabetically if(sortBy==SORT_BY.ByTitle) { returnBookTitle.compareTo(((Book)objToCompare).BookTitle); } else//SortbyBookprice { returnInteger.valueOf(Price-((Book)objToCompare).Price); } } } Asyoucanseeinabovecode,wearesortingonthebasisofeitherBookTitleorPrice.Thelogiccanbeanythingdependingonbusinessrequirement. RunningthesamplecodeinDeveloperConsole: Runbelowcodein“DeveloperConsole”frombrowseror“ExecuteAnonymous”fromEclipse. Book[]books=newBook[]{ newBook('SalesforceHandbook','JeffDouglas',360,35,Date.newInstance(2011,03,20)), newBook('LetUsC','YashavantP.Kanetkar',593,58,Date.newInstance(2008,03,21)), newBook('HeadFirstDesignPatterns','ElisabethFreeman',678,28,Date.newInstance(2004,11,01)) }; Book.sortBy=Book.SORT_BY.ByTitle; books.sort(); System.debug(books); Book.sortBy=Book.SORT_BY.ByPrice; books.sort(); System.debug(books); Whenyouwillseetheoutput,firsttimeitsortedbyBookTitleandsecondtimeitissortedaccordingPrice. Ihopethispostwillbehelpfultomanysalesforcedevelopers. Happycoding!!! SharethispostClicktoemailthistoafriend(Opensinnewwindow)ClicktoshareonTwitter(Opensinnewwindow)ClicktoshareonFacebook(Opensinnewwindow)ClicktoshareonLinkedIn(Opensinnewwindow)ClicktoshareonPinterest(Opensinnewwindow)ClicktoshareonTumblr(Opensinnewwindow)ClicktoshareonReddit(Opensinnewwindow)ClicktoshareonPocket(Opensinnewwindow) 14comments Hi,IamnotabletounderstandhowisthemethodreturningcompareToresults? Reply Hi,Forstringwealreadyhavecomparetomethodswhichreturnseither0,1.Incaseofintegerswearehandlingthosevaluebyourselfonly. Reply doesanybodytriedtocover100%ofthissamplecodewhiletesting? Reply Thisarticleisverynice Reply Thankyouforthis,itisveryuseful.Anychancetopickyourbrainonhowtosortbytwowrapperproperties?sofirstBookTitle,thenBookPrice…anycommentswouldbeappreciated. Reply Thanksdude.Itisgoodpeaceofcode. Reply Isthereanywaythatwecanspecifysortingorderlikeascendingordescendingorder? Reply Yes, Itsuptoyouhowyoureturnthevalueinmethod“compareTo”. Justchangethelogicandgo.. Reply HiJitendra, Canupleaseguideme…Ihavefollowedthestepsforwrappersortinganditsworkinggreatinatabledoen’thaveanynullvalues…butinmytablehavingnullvaluesforfewcolumnsthenitsgivingerrors…Pleaseseemypieceofcode. globalwithsharingclassActivitiesCollectionimplementsComparable{ publicstringtype{get;set;} } publicenumSORT_BY{ ByType } publicenumOrder_By{ ascend,descend } globalintegercompareTo(ObjectobjToCompare){ if(typo!=null&&typo!=”&&type!=null&&type!=”&&sortBy==SORT_BY.ByType&&orderBy==Order_BY.ascend) returntype.compareTo(typo); elseif(typo!=null&&typo!=”&&type!=null&&type!=”&&typo!=‘–None–‘&&sortBy==SORT_BY.ByType&&orderBy==Order_BY.descend) } returntypo.compareTo(type); } Pleasehelpme. Reply Hi, Abovecodeisnotcomplete.Whatistypoandhowyouarecomparingobject“objToCompare”? Pleasepostcompletecode. Reply cananyonewillpleasedothisVFpagecontroller,ifanyquestionpleaseaskmeaboutthisVFpage Reply Howcanthisbechangedtodescendingorder? Reply whatifIwanttocomparebybothi.e1stpriceandthenname Reply Howthedatecomparetoisgoingtoworkhere,letssayifiwanttocomparebypublishingDate? Reply LeaveacommentCancelreplyYouremailaddresswillnotbepublished.Requiredfieldsaremarked*CommentName* Email* Website Notifymeoffollow-upcommentsbyemail.Notifymeofnewpostsbyemail. Δ ThissiteusesAkismettoreducespam.Learnhowyourcommentdataisprocessed. Postnavigation PreviouspostSalesforceInterviewQuestions–Part10NextpostSalesforceInterviewQuestions–Part11 SearchBlogContent SubscribetoBlogviaEmail Nevermissapost.Provideyouremailaddresstogetlatestblogposts,rightintoyouremailbox. Join1,837othersubscribers EmailAddress Subscribe Archive Archive SelectMonth December2021 (1) August2021 (2) June2021 (1) December2020 (1) July2020 (2) June2020 (4) May2020 (2) April2020 (3) March2020 (1) February2020 (1) January2020 (4) December2019 (1) October2019 (2) September2019 (1) June2019 (2) April2019 (1) March2019 (2) February2019 (4) January2019 (3) October2018 (1) September2018 (2) August2018 (1) July2018 (4) June2018 (3) May2018 (1) April2018 (2) March2018 (5) February2018 (1) January2018 (1) December2017 (2) November2017 (4) October2017 (3) September2017 (3) August2017 (4) July2017 (3) June2017 (3) May2017 (5) April2017 (1) March2017 (4) January2017 (2) December2016 (4) November2016 (4) September2016 (5) August2016 (3) July2016 (1) June2016 (4) May2016 (2) April2016 (2) March2016 (3) February2016 (6) January2016 (10) December2015 (5) November2015 (2) October2015 (6) September2015 (4) August2015 (3) July2015 (9) June2015 (4) May2015 (9) April2015 (3) March2015 (5) February2015 (2) January2015 (2) December2014 (4) November2014 (4) August2014 (1) July2014 (4) April2014 (6) February2014 (9) January2014 (2) December2013 (1) November2013 (3) October2013 (5) September2013 (1) August2013 (1) July2013 (5) June2013 (3) May2013 (5) March2013 (2) February2013 (5) December2012 (1) September2012 (7) August2012 (4) July2012 (4) June2012 (8) May2012 (5) April2012 (3) March2012 (4) February2012 (3) January2012 (7) December2011 (5) November2011 (3) October2011 (2) September2011 (5) August2011 (7) July2011 (3) June2011 (8) May2011 (8) April2011 (18) March2011 (31) February2011 (24) December2010 (7) November2010 (2) October2010 (15) September2010 (35) August2010 (26) July2010 (36) June2010 (14) May2010 (27) DarkMode: SendtoEmailAddress YourName YourEmailAddress Cancel Postwasnotsent-checkyouremailaddresses! Emailcheckfailed,pleasetryagain Sorry,yourblogcannotsharepostsbyemail.



請為這篇文章評分?