Apex Sorting Objects with Comparable Interface

Sorting objects generic class

public abstract class Comparator {
    public abstract Integer compare(Object o1, Object o2);
    public static void sort(Object[] values, Comparator comp) {
        //  Obtain the list type of values
        Object[] temp = values.clone();
        temp.clear();
        //  Helper class for sorting using Comparable
        Helper[] tempValues = new Helper[0];
        for(Object value: values) {
            tempValues.add(new Helper(comp, value));
        }
        //  Perform sort
        tempValues.sort();
        //  Extract values back into temp list
        for(Helper helper: tempValues) {
            temp.add(helper.value);
        }
        //  And set the list to the new, sorted order
        values.clear();
        values.addAll(temp);
    }
    //  Simply calls Comparator when asked.
    class Helper implements Comparable {
        Comparator method;
        Object value;
        Helper(Comparator comp, Object val) {
            method = comp;
            value = val;
        }
        public Integer compareTo(Object o) {
            return method.compare(value, ((Helper)o).value);
        }
    }
}

Compare Strings

public class AccountNameComparator extends Comparator {
    public override Integer compare(Object a, Object b) {
        return ((Account)a).name.compareTo(((Account)b).name);
    }
}

Compare Dates

public class PriceHistoryPriceDateCompare extends Comparator {
    public override Integer compare(Object a, Object b) {
      return (DateTime.newInstance(((History__c)a).Price_Date__c.year(), ((History__c)a).Price_Date__c.month(),1).getTime().format()).compareTo((DateTime.newInstance(((History__c)b).Price_Date__c.year(), ((History__c)b).Price_Date__c.month(), 1).getTime()).format());
    }
	}

Test Class

@isTest(SeeAllData=true) static void testComparator(){
		List<Account> accountToSort = new List<Account>();
		for (Integer k = 70;k > 64;k--){
			Account acc = (Account)SmartFactory.createSObject('Account');
			acc.Name = String.fromCharArray(new List<integer> {k});
			insert acc;
			accountToSort.add(acc);
		}

		Test.startTest();
    	Comparator.sort(accountToSort, new AccountNameComparator());
			System.assertEquals(accountToSort.get(0).Name, 'A');
			System.assertEquals(accountToSort.get(1).Name, 'B');
			System.assertEquals(accountToSort.get(2).Name, 'C');
			System.assertEquals(accountToSort.get(3).Name, 'D');
			System.assertEquals(accountToSort.get(4).Name, 'E');
			System.assertEquals(accountToSort.get(5).Name, 'F');
		Test.stopTest();
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: