Reverse list in Apex

Can you reverse a list of objects in Apex?

In Java and C#, there is a method you can call to reverse a list but I don’t see one for Apex…

Answer

No such method currently exists on the List class as of Winter ’17 (API v38). The only way to do this in Apex that I’m aware of is to loop over the list starting from the end.

List<Object> someList = new List<Object>{1,2,3,4,5};
List<Object> reversed = new List<Object>();

for(Integer i = someList.size() - 1; i >= 0; i--){
    reversed.add(somelist[i]);
}

If you’re storing instances of an Apex class in a list, you could over-engineer a solution by using the strategy pattern and implementing the Comparable interface so you can use the sort() method with different sort orders.

A crude example

public class IntWrapper implements Comparable{
    public Integer int;
    public static String order = 'ASC';
    
    public IntWrapper(Integer val){
        int = val;
    }

    public Integer compareTo(Object input){
        Integer result;
        if(IntWrapper.order == 'ASC'){
            result = compareASC(input);
        } else {
            result = compareDESC(input);
        }
        return result;
    }

    private Integer compareASC(Object input){
        Integer intIn = (Integer)input;
        if(int < intIn){
            return -1;
        } else if(int > intIn){
            return 1;
        } else {
            return 0;
        }
    }

    private Integer compareDESC(Object input){
        Integer intIn = (Integer)input;
        if(int < intIn){
            return 1;
        } else if(int > intIn){
            return -1;
        } else {
            return 0;
        }
    }
}

List<IntWrapper> someList = new List<IntWrapper>{new IntWrapper(1), new IntWrapper(2), new IntWrapper(3), new IntWrapper(4), new IntWrapper(5)};

// First sort ensures we're in ASC order
someList.sort();

// Set the static flag, sort again, et voila, list is reversed
IntWrapper.order = 'DESC';
someList.sort();

Reversing insertion order like this is possible, but you’d need an extra integer in your class to hold the list index, and something like an addToList(someList) method that would set the list index to someList.size() before adding it to the list.

+edit:

This general method, having a wrapper class that implements Comparable, can also be used for defining custom sort orders for sObjects as well. There’s even supporting documentation

Attribution
Source : Link , Question Author : akcorp2003 , Answer Author : Community

Leave a Comment