Skip to content

Instantly share code, notes, and snippets.

@hasanthaera
Last active August 29, 2015 14:19
Show Gist options
  • Save hasanthaera/6fbb48bc9933b0561263 to your computer and use it in GitHub Desktop.
Save hasanthaera/6fbb48bc9933b0561263 to your computer and use it in GitHub Desktop.
Salesforce - compare values through list of objects
List<Sobject> sObjectList = <---provide list of Objects eg: Schools--->
String orderBy = <---provide orderBy field Name eg: School Name--->
String order = <--ASC or DESC--->
List<Sobject> resultList = new List<Sobject>();
Map<object, List<Sobject>> sortMap = new Map<object, List<Sobject>>();
if(sObjectList.isEmpty() || orderBy || order) return;
for(Sobject ob : sObjectList){
if(sortMap.get(ob.get(orderBy)) == null)
sortMap.put(ob.get(orderBy), new List<Sobject>());
sortMap.get(ob.get(orderBy)).add(ob);
}
//Sort the keys
List<object> keys = new List<object>(sortMap.keySet());
keys.sort();
for(object key : keys){
resultList.addAll(sortMap.get(key));
}
//create sorted list
sObjectList.clear();
if(order.toLowerCase() == 'ASC'){
for(Sobject ob : resultList){
sObjectList.add(ob);
}
}else if(order.toLowerCase() == 'DESC'){
for(integer i = resultList.size()-1; i >= 0; i--){
sObjectList.add(resultList[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment