function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Suraj_BahaleSuraj_Bahale 

How to implement sorting (Descending to Ascending) in Apex Controller?

I tried to get data from the controller only by using "ORDER BY DESC" but I used two queries so it's sorting but dividing report into two sections...

Since I used Map so it does not support Sort()...

How can I sort all data in the controller, by Descending to Ascending?

Source Code:
list<Account> ShipToAccList = [Select ID from Account WHERE ParentID =: accId];
	//Previous Year
		list<AggregateResult> PrevYear_AGG = [Select CC_Product__r.ccrz__SKU__c PRODUCTSKU, 
												SUM(Quantity_Shipped__c) QTYSHIPPED 
												FROM
												CC_Shipment_Line_Items__c 
												WHERE CC_Shipment__r.Account__c IN : ShipToAccList  
												AND CC_Shipment__r.Date_Shipped__c >= LAST_YEAR 
												AND CC_Shipment__r.Date_Shipped__c < THIS_YEAR GROUP BY CC_Product__r.ccrz__SKU__c 
												ORDER BY SUM(Quantity_Shipped__c) DESC];

	set<string> productset = new set<string>();
	for(AggregateResult aggrstlst : PrevYear_AGG){
		if(!(productset).contains((string)aggrstlst.get('PRODUCTSKU'))){
			productset.add((string)aggrstlst.get('PRODUCTSKU'));    
		}        
	}

	//Current Year
	list<AggregateResult> CurrYear_AGG = [Select CC_Product__r.ccrz__SKU__c PRODUCTSKU, SUM(Quantity_Shipped__c) QTYSHIPPED 
										  FROM  CC_Shipment_Line_Items__c 
										  WHERE
										  CC_Shipment__r.Account__c IN : ShipToAccList
										  AND CC_Shipment__r.Date_Shipped__c = THIS_YEAR
										  GROUP BY CC_Product__r.ccrz__SKU__c
										  ORDER BY SUM(Quantity_Shipped__c) DESC
										 ];

	//Get Aggregate values in a Map
	Map<string,object> AG_Map = new Map<string,object>();

	//Mapping :: Previous year
	for(AggregateResult aggrstlst : PrevYear_AGG){ 
		
		list<integer> prvlist = new list<integer>();
		// prev yr
		prvlist.add(integer.valueOf((Double)aggrstlst.get('QTYSHIPPED')));
		//curr yr
		prvlist.add(0);
		
		AG_Map.put((string)aggrstlst.get('PRODUCTSKU') , prvlist);
	}
	//system.debug(AG_Map);

	//Mapping :: Current year
	for(AggregateResult aggrstlst : CurrYear_AGG){
		if((AG_Map.keySet()).contains((string)aggrstlst.get('PRODUCTSKU'))){// if Product FOUND in AG_MAP    
			((list<object>)AG_Map.get((string)aggrstlst.get('PRODUCTSKU')))[1] = integer.valueOf((Double)aggrstlst.get('QTYSHIPPED')); 
			
		} 
		else{// if Product not in AG_MAP
			list<integer> prvlist = new list<integer>();
			// prev yr
			prvlist.add(integer.valueOf((Double)aggrstlst.get('QTYSHIPPED')));
			//curr yr
			prvlist.add(0);
			
			AG_Map.put((string)aggrstlst.get('PRODUCTSKU'), prvlist);
		}
	}
	  
	//GETTING PROD DESCRITION AND FAMILY
	Map<string,list<object>> ProdDetailsMap = new Map<string,list<object>>();
	for(ccrz__E_Product__c ProdInst : [SELECT ID, PCC_Family_Name__c,
									   ccrz__ShortDescRT__c,ccrz__SKU__c 
									   FROM ccrz__E_Product__c 
									   WHERE ccrz__SKU__c IN : AG_Map.keySet()]){
										   list<object> ProdD = new list<object>();
										   prodD.add(ProdInst.ccrz__ShortDescRT__c);
										   prodD.add(ProdInst.PCC_Family_Name__c);    
										   ProdDetailsMap.put(string.valueof(ProdInst.ccrz__SKU__c), ProdD);
									   }

	//Final Respoonse Map
	list<object> YOYPrimary = new list<object>();

	Map<integer, list<object>> beforesrt = new Map<integer, list<object>>();

	for(string objlst : AG_Map.keySet()){
		list<object> YOYinstance = new list<object>();
		
		AG_Map.get(objlst);
		
		//Allign prod SKU, desc and familiy
		string ProductSKU = string.valueOf(objlst);
		YOYinstance.add(ProductSKU);
		String PartDescription = string.valueOf(((list<object>) ProdDetailsMap.get(objlst))[0]);
		YOYinstance.add(PartDescription);
		string ProductFamilily;
		if(string.isBlank((string.valueOf(((list<object>) ProdDetailsMap.get(objlst))[1])))){
			ProductFamilily = 'NOT AVAILABLE';
		}else{
			ProductFamilily = string.valueOf(((list<object>) ProdDetailsMap.get(objlst))[1]);    
		}                
		YOYinstance.add(ProductFamilily);
		
		//calculate difference
		integer CYQty = integer.valueOf(((list<object>)AG_Map.get(objlst))[1]);
		YOYinstance.add(CYQty);
		integer LYQty = integer.valueOf(((list<object>)AG_Map.get(objlst))[0]);
		YOYinstance.add(LYQty);
		
		integer QtyDiff = CYQty - LYQty;                
		YOYinstance.add(QtyDiff);

		//calculate %difference 
		double PercentDiff = (decimal.valueof(QtyDiff)/decimal.valueof(LYQty))*100;
		YOYinstance.add(PercentDiff);

		YOYPrimary.add(YOYinstance);
		//####### MAP OF UNSORTED ######
		beforesrt.put(LYQty, YOYinstance);
	}
				
	//########### RESPONSE SECTION ###############################
	Map<string, object> responseYOY = new Map<string, object>();            
	responseYOY.put('YOYrecords', YOYPrimary);

	returnMap.put('YOYPrimary', YOYPrimary);

	res.success	= true;
	res.data 	= returnMap;

 
Best Answer chosen by Suraj_Bahale
AnudeepAnudeep (Salesforce Developers) 
Hi Suraj - To do the sorting, you need to sort your map. However, maps does not support sorting by value. Look at the following sorting techniques below

Example 1: 
Public class mapsort
{
	public mapsort()
	{

		map<String , Integer> accMap = new Map<String,Integer>();
		accMap.put('Id2',2);
		accMap.put('Id1',1);
		accMap.put('Id4',4);
		accMap.put('Id3',3);
		accMap.put('Id5',5);

		List<String> aList = new List<String>();
		aList.addAll(accMap.keySet());
		aList.sort();
		//so here you will get sorted total base on key
		for(String a: aList)
		{
		   System.debug( '::::::::::::: ' + accMap.get(a)) ;
		}
	}

}

Example 2:
 
Map<String, List<String>> myMap = new Map<String, List<String>>();
List<Sring> myList1 = new List<String>{'1', '2', '3'};
List<String> myList2 = new List<String>{'4', '5', '6'};
myMap.put('1', myList1);
myMap.put('2', myList2);

//Construct a list from the map keyset and sort it
List<String> keyList = new List<String>();
keyList.addAll(myMap.keySet());
keyList.sort();

//Loop through the sorted keys
for (String key : keyList) {
    List<String> value = myMap.get(key);
}

Or you can sort using a wrapper class. See this blog