How to sort list of custom or standard object records

How to sort list of custom or standard object records

Sample Code:
Visualforce page:
<apex:page sidebar=”false” Controller=”Sample” showHeader=”true” id=”pg”>
    <apex:pageBlock >
        <apex:pageBlockTable value=”{!memList}” var=”m”>
            <apex:column value=”{!m.Name}”/>
            <apex:column value=”{!m.Age__c}”/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Apex Controller:
public class Sample {   
    public List<Member__c> memList {get;set;}
    List<MemberWrapper> memberWrapperList = new List<MemberWrapper>();
    public sample() {
        memList = new List<Member__c>();
        memList = [SELECT Name, Age__c FROM Member__c];
        
        for(Member__c mem : memList){
            memberWrapperList.add(new MemberWrapper(mem));
        }
        
        memberWrapperList.sort();
        memList.clear();
        
        for(MemberWrapper MW : memberWrapperList){
            memList.add(MW.member);
        }
    }
    
    public class MemberWrapper implements Comparable {

        public Member__c member = new Member__c();
        
        // Constructor
        public MemberWrapper(Member__c memberRecord) {
            member = memberRecord;
        }
        
        // Compare members based on the Member__c Age.
        public Integer compareTo(Object compareTo) {
            // Cast argument to MemberWrapper
            MemberWrapper compareTomember = (MemberWrapper)compareTo;
            
            // The return value of 0 indicates that both elements are equal.
            Integer returnValue = 0;
            if (member.Age__c > compareTomember.member.Age__c) {
                // Set return value to a positive value.
                returnValue = 1;
            } else if (member.Age__c < compareTomember.member.Age__c) {
                // Set return value to a negative value.
                returnValue = -1;
            }
            
            return returnValue;       
        }
    }
}

Output:

Leave a Reply