2

Lets say I have a list of a sObject with several records which have a some same values in a field/column. What is the fastest way to reproduce a new list with only unique values for this list.

Record List
ID Name AGE
0  A    18
1  B    19
2  C    19
3  D    21
4  E    21

Result List (based on age)
ID Name AGE
0  A    18
1  B    19
3  D    21
3
  • Are the records sObjects or custom Apex classes?
    – David Reed
    May 23 '18 at 2:09
  • @DavidReed sObjects.
    – Thomas
    May 23 '18 at 2:14
  • you can filter your list after gathering it. might be less efficient - or map them using the age as your key.
    – Ronnie
    May 23 '18 at 2:17
5

Whenever you need a unique anything, you need a Set or a Map, depending on the circumstances. For example, unique values by Age:

Map<Decimal, SObjType> uniqueAges = new map<Decimal, SObjType>();
for(SObjType record: recordList) {
  if(!uniqueAges.containsKey(record.Age__c)) {
      uniqueAges.put(record.Age__c, record));
  }
}
SObjType[] uniqueList = uniqueAges.values();

This is obviously more pseudo-code, but you should be able to work it out from here.


More generically, you can write a method for this:

public static SObject[] getUniqueValues(SObject[] records, SObjectField field) {
    Map<Object, SObject> uniqueValues = new Map<Object, SObject>();
    for(SObject record: records) {
        if(!uniqueValues.containsKey(record.get(field))) {
            uniqueValues.put(record.get(field), record);
        }
    }
    return uniqueValues.values();
}
0

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.