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
Hitesh chaudhariHitesh chaudhari 

Sort Map using its object field

How to sort map if we want to sort it by perticular field ;

Following is the map I am refering :

Map< BMCServiceDesk__BMC_BaseElement__c , String> mymap= new Map< BMCServiceDesk__BMC_BaseElement__c , String>();

I want to sort by its key's respective field as my map's key is an field  i want to sort by Custom Field of Obj.

For Example : If my obj is Myobj i want it ot sort by its field called as Myobj.CustomField
Best Answer chosen by Hitesh chaudhari
Steven NsubugaSteven Nsubuga
A Map by definition cannot be sorted. 
  1. What you can do is to retrieve a Set from the keyset method of the map, add these set elements to a list.
  2. Sort the list, see https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm.
  3. Use the sorted list to retrieve items from the map in order
List<BMCServiceDesk__BMC_BaseElement__c> baseElements = new List<BMCServiceDesk__BMC_BaseElement__c>();
baseElements.addAll(mymap.keyset());
baseElements.sort();

// To retrieve map elements in order, use the set
for (BMCServiceDesk__BMC_BaseElement__c element : baseElements){
     String x = mymap.get(element);
}