Created
May 22, 2021 15:30
-
-
Save skysan87/65f0183cc12fa829cfb642e642b829ad to your computer and use it in GitHub Desktop.
[Salesforce][Apex] how to sort a List by any property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomList { | |
private Map<String, Object> innerlist = new Map<String, Object>(); | |
public void add(Object obj) { | |
this.innerlist.put(obj.hashCode().format(), obj); | |
} | |
public List<Object> sortBy(String propertyName) { | |
String str = JSON.serialize(this.innerlist); | |
// NOTE: key is hashcode | |
Map<String, Object> jsonMap = (Map<String, Object>) JSON.deserializeUntyped(str); | |
List<String> hashList = new List<String>(); | |
hashList.addAll(jsonMap.keySet()); | |
List<Object> sortList = new List<Object>(); | |
// NOTE: key is (hashcode + target property) | |
Map<String, String> valueKeyMap = new Map<String, String>(); | |
for (String key : hashList) { | |
Map<String, Object> objmap = (Map<String, Object>) jsonMap.get(key); | |
sortList.add(objmap.get(propertyName)); | |
valueKeyMap.put(String.format('{0}{1}', new List<Object>{key, objmap.get(propertyName)}), key); | |
} | |
// sort | |
sortList.sort(); | |
Map<String, Object> result = new Map<String, Object>(); | |
for (Object propValue: sortList) { | |
for (String key : hashList) { | |
String targetKey = valueKeyMap.get(String.format('{0}{1}', new List<Object>{key, propValue})); | |
if (targetKey != null && !result.containsKey(key)) { | |
result.put(key, this.innerlist.get(key)); | |
break; | |
} | |
} | |
} | |
return result.values(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CustomObject obj1 = new CustomObject(); | |
obj1.Name = 'bbb'; | |
obj1.Id = 88; | |
CustomObject obj2 = new CustomObject(); | |
obj2.Name = 'aaa'; | |
obj2.Id = 100; | |
CustomObject obj3 = new CustomObject(); | |
obj3.Name = 'ccc'; | |
obj3.Id = 1; | |
CustomList listA = new CustomList(); | |
listA.add(obj1); | |
listA.add(obj2); | |
listA.add(obj3); | |
List<CustomObject> sortNameList = new List<CustomObject>(); | |
for(Object obj: listA.sortBy('Name')) { | |
sortNameList.add((CustomObject)obj); | |
} | |
System.debug(sortNameList); // result: obj2, obj1, obj3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment