2

I am creating a map from a string stored in a specific format. But Adding the key-value pairs and later displaying it, I notice the order is not maintained on the map. Is it possible to maintain the order in which key-value pairs are added.

Map<String, String> FieldLabelMap = new Map<String, String>();
    String fields = 'status,Status;Reason,Type;CaseNumber,Case Number;SecondaryReason,Case Reason';
    List<String> fieldAPIList = fields.split(';');
    system.debug('list#'+fieldAPIList[0]);
    for(String fieldvar : fieldAPIList){
        List<String> Stringvar = fieldvar.split(',');
        system.debug(Stringvar[0]+'#'+Stringvar[1]);
        FieldLabelMap.put(Stringvar[0],Stringvar[1]);  
    }
    system.debug('##FieldLabelMap'+FieldLabelMap);

    output : ##FieldLabelMap{CaseNumber=Case Number, Reason=Type, Secondary_Case_Layout__c=Case Reason, status=Status}
3

Maps are unordered collections, and may be organized in any order. Note that Iteration Order for Maps and Sets Is Now Predictable causes the values to be displayed in a consistent order, which is why they appear to be ordered alphabetically. If you want the order to definitely be preserved, return the keys in the order you would like.

public class ReturnValue {
  @AuraEnabled String[] keys;
  @AuraEnabled Map<String, String> values;
}

@AuraEnabled
public static ReturnValue fetchLabelsMap() {
    ReturnValue fieldValues = new ReturnValue();
    fieldValues.keys = new String[0];
    fieldValues.values = new Map<String, String>();
    String fields = 'status,Status;Reason,Type;CaseNumber,Case Number;SecondaryReason,Case Reason';
    List<String> fieldAPIList = fields.split(';');
    for(String fieldvar : fieldAPIList){
        List<String> Stringvar = fieldvar.split(',');
        fieldValues.keys.add(Stringvar[0]);
        fieldValues.values.put(Stringvar[0],Stringvar[1]);  
    }
    return fieldValues;
}
| improve this answer | |
  • Thanks a lot. Will check and update. – Pankaj Andhale Jun 12 at 12:53
  • Thanks a lot, you are great !! – Pankaj Andhale Jun 15 at 9:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.