How to sort by two fields using Comparable interface

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

Any feedback on how to sort by a second field (size) so I can keep each product group in the proper order by size would be appreciated. apex. SalesforceStackExchangeisaquestionandanswersiteforSalesforceadministrators,implementationexperts,developersandanybodyin-between.Itonlytakesaminutetosignup. Signuptojointhiscommunity Anybodycanaskaquestion Anybodycananswer Thebestanswersarevotedupandrisetothetop Home Public Questions Tags Users Unanswered FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HowtosortbytwofieldsusingComparableinterface AskQuestion Asked 3years,8monthsago Active 3years,8monthsago Viewed 1ktimes 3 1 Icreatedagenericsortingutilityusingthecomparableinterfacetotestsortingbyproductname: publicclassGenericSortingUtil{ publicvirtualclassObjWrapperimplementsComparable{ publicsObjectobj; publicObjWrapper(){} publicObjWrapper(Sobjectobj){ this.obj=obj; } publicvirtualIntegercompareTo(ObjectcompareTo){ ObjWrappercompareToObj=(ObjWrapper)compareTo; if((String)obj.get('Name')>(String)compareToObj.obj.get('Name')){ return1; } if((String)obj.get('Name')==(String)compareToObj.obj.get('Name')){ return0; } return-1; } } publicstaticListgetProducts(){ Listresults=newList(); for(Product2p:[selectName,ProductCode,Size__cfromProduct2limit100]){ results.add(newObjWrapper(p)); } returnresults; } } Childclasss: publicclassShirtWrapperextendsGenericSortingUtil.ObjWrapper{ publicoverrideIntegercompareTo(ObjectcompareTo){ ShirtWrappercompareToObj=(ShirtWrapper)compareTo; integernameOrder=super.compareTo(compareTo); returnnameOrder==0?getSizeOrder(String.valueOf(obj.get('Size__c')))-getSizeOrder(String.valueOf(compareToObj.obj.get('Size__c'))):nameOrder; } publicIntegergetSizeOrder(stringsize){ Integerretval=-1; switchonsize{ when'S'{ retval=0; } when'M'{ retval=1; } when'L'{ retval=2; } when'XL'{ retval=3; } whenelse{ returnretval; } } returnretval; } } Icanrunthecodeintheanonymouswindowandgetthecorrectresults: Listresults=GenericSortingUtil.getProducts(); results.sort(); for(GenericSortingUtil.ObjWrapperow:results){ system.debug('*********************'+ow.obj.get('Name')); } I'mtryingtodeterminehowIcansortbytwofieldssothateachproductgroupingcanbesortedbysize.Theproductsareclothingitems.Eachproducthasaseriesofsizes.Forsimplicity,thesizesareS,M,L,XL.WhatIamtryingtoachieveissortbythesizefieldaswellastheproductname. Forexample,ifIhavethefollowingproducts:black.v-neck.s,black.v-neck.m,black.v-neck.l,andblack.v-neck.xl.Iwouldwantthemsortedbysmallesttolargest: black.v-neck.s black.v-neck.m black.v-neck.l black.v-neck.xl Thereisasize__cfieldforeachproductthatholdsthesizevalue. Anyfeedbackonhowtosortbyasecondfield(size)soIcankeepeachproductgroupintheproperorderbysizewouldbeappreciated. apex Share Improvethisquestion Follow editedJun11,2018at17:02 Dman100 askedJun10,2018at17:42 Dman100Dman100 2,32522goldbadges3434silverbadges6969bronzebadges Addacomment  |  1Answer 1 Active Oldest Votes 3 Ithinkyourbestbetisgoingtobetoextendyourexistingclass,andimplementtheextralogicinthechildclass. publicclassShirtWrapperextendsObjWrapper{ publicIntegercompareTo(ObjectcompareTo){ ShirtWrappercompareToObj=(ShirtWrapper)compareTo; integernameOrder=super.compareTo(compareTo); returnnameOrder==0? getSizeOrder(String.valueOf(obj.get('Size__c')))-getSizeOrder(String.valueOf(compareToObj.get('Size__c'))) :nameOrder; } publicstaticintegergetSizeOrder(stringsize){ switchonsize{ when'S'{return0;} when'M'{return1;} when'L'{return2;} when'XL'{return3;} whenelse{thrownewBadSizeException();} //Ihaven'ttestedwhetherthecompilerwillcomplainthisdoesn'talwaysreturn, //ifitdoesyoucanmovethethrowtothebottomofthemethod. } } Share Improvethisanswer Follow editedJun15,2018at1:54 answeredJun10,2018at18:04 IllusiveBrianIllusiveBrian 4,01811goldbadge1111silverbadges2222bronzebadges 3 3 switchonuseswhenandwhenelsetoavoidcollisionwithexistingsObjectnames. – DavidReed ♦ Jun10,2018at18:37 @DavidReedCorrected,IonlyheardtheyimplementedswitchyesterdayandI'meagertostartusingitonMonday. – IllusiveBrian Jun11,2018at1:12 Hi@DavidReed,thanksfortheexample.Iincludedthemodifiedcodeabove.ImadetheObjWrapperclassvirtualsoIcouldextenditintheShirtWrapperclassandImadethecompareTomethodvirtualsoIcouldoverrideit.Isthisthecorrectimplementationyouwereindicating?Iamtryingtorunthecodeintheanonymouswindow,butdoIneedtopasstheresultsfromtheObjWrappersortintotheShirtWrapper? – Dman100 Jun11,2018at17:09 Addacomment  |  YourAnswer ThanksforcontributingananswertoSalesforceStackExchange!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedapexoraskyourownquestion. TheOverflowBlog TwiliolaunchesCollectiveonStackOverflow Stopaggregatingawaythesignalinyourdata FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Related 7 'Comparable'interface-whyglobal 1 Gettingerror"System.LimitException:Toomanyqueryrows:50001"whatidointhiscase. 8 SimpleApexclasstoreturnalistofstrings 3 Howtousecomparableinterfacetosortalist? 7 Significantelapsedtimedifferenceswhencallingsort()ondifferentComparableimplementations 4 MapWhereKeyisadifferentSObject 0 ComparableInterfacenotsorting 0 SortingakeySet HotNetworkQuestions HasNATOeverstartedawar? Crateartstacking Cananyonehelpmeidentifytheset?Red,White,andBlue(mostly) HowtotacklethisVRPvariant? Sourcingareplacementtrestletablelockingpin(metal) Doestheouterdiameterof4.78indicateanM4oranM5bolt? Howtomakethisrendermorerealistic(CellMaterial) Adverbialclauseasantecedentofpronoun? Isitfirsttimeinhistorythatongoingwarwashaltedforfewhourstoevacuatepeople? Laggytexteditor Isthereafunctionalreasonforwizardstoliveintowerssooften? IsthereaGermancolloquialismtodefineapersonworkingmainlywithpapersanddocuments? Isitpossibletocontrolthefrequencyoflight? WhattypeofconnectorcanIuseforrepetitivetestingofboardwithstandardheaders? Whyisn'tthereauniversalinvestmentstandard/benchmark? Gamewhereanalien(antagonist)racegotsmarterincombat Isitfairtoassumethat站and占arethesameword? Howdoesamilitaryfightwhiletryingnottobenuked? InwhatapplicationsdowepreferModelSelectionoverModelAveraging? Howdoyousolvevaguemateintwoproblems? HowtoManipulateaSimpleListofVectors? PotentialcounterexamplestoBass'traceconjecture ProceduralChronoTriggerportal CanIrunbothaprimaryandsecondaryDNSserverusingthesamepublicIP? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?