Sunday, April 8, 2018

Comparable Interface : Way to perform sorting on wrapper class (non-primitive type that is Lists of user-defined types)

Apex provides comparable interface with compareTo method which can be used sort wrapper class.

You can write your comparison logic in compareTo method to sort wrapper.

Below is sample wrapper class, user-defined data type which implements comparable interface.


Below is sample code which you can run in developer console in execute anonymous block.

List<SK_sortUtilityTestWrapper> wrapperList= new List<SK_sortUtilityTestWrapper>();
wrapperList.add(new SK_sortUtilityTestWrapper('D',50.6));
wrapperList.add(new SK_sortUtilityTestWrapper('A',40));
wrapperList.add(new SK_sortUtilityTestWrapper('B',44.2));
system.debug('****wrapperlist before sorting:'+wrapperList);
wrapperList.sort();
system.debug('****wrapperlist after sorting:'+wrapperList);


Logs:


Hope this will help!!!


No comments:

Post a Comment