function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
inbox outbox 7inbox outbox 7 

How to reverse a list?

Please correct my code and advice me on what I am doing wrong.
public List<Account> sortingMethod1() {
            List<Account> accList= new List<Account>();
            accList.add(new Account(Name= 'a'));
            accList.add(new Account(Name= 'z'));
            accList.add(new Account(Name= 'c'));
            accList.add(new Account(Name= 'd'));
            accList.add(new Account(Name= 'p'));
            accList.add(new Account(Name= 'n'));
            INSERT accList;
    
            List<Account> reversedList= new LIst<Account>();
            for(integer I= accList.size()-1; i>=0; i--){
                reversedList.add(accList.get(I));
            }
    
            return reversedList;
        }

 
Maharajan CMaharajan C
Hi,

Your code is already returning the list in reverse manner only.  or you want to arrange account names in orderly and revised.
 
public List<Account> sortingMethod1() {
	List<Account> accList= new List<Account>();
	accList.add(new Account(Name= 'a'));
	accList.add(new Account(Name= 'z'));
	accList.add(new Account(Name= 'c'));
	accList.add(new Account(Name= 'd'));
	accList.add(new Account(Name= 'p'));
	accList.add(new Account(Name= 'n'));
	accList.sort();

	INSERT accList;

	system.debug(' accList --> ' + accList );
	List<Account> reversedList= new LIst<Account>();
	for(integer I= accList.size()-1; i>=0; i--){
		reversedList.add(accList.get(I));
	}

	system.debug('reversedList--> ' + reversedList );

	return reversedList;
}


Thanks,
Maharajan.C