0

I am trying to figure it out how to sort a list of list using apex, like for example :

Input : [[5, 'text1], [1, 'text2'] , [12, 'text3]]

To obtain and ascending ordered list like that :

Output: [ [1, 'text2'], [5, 'text1] , [12, 'text3] ]

I have researched around and I have found a way in Java but really nothing clear about apex. Any help would be really appreciated it! Thanks so much!!

0
5

You can implement Comparable interface for your custom class and determine your rule in compareTo method.

public class ListItem implements Comparable {
    public Integer first {get; set;}
    public String second {get; set;}
    
    public ListItem(Integer first, String second){
        this.first = first;
        this.second = second;
    }
    
    public Integer compareTo(Object compareTo) {
        ListItem compareToItem  = (ListItem)compareTo;
        return this.first - compareToitem.first;
    }
}

Usage:

ListItem firstItem = new ListItem(5, 'text1');
ListItem secondItem = new ListItem(1, 'text2');
ListItem thirdItem = new ListItem(12, 'text3');

List<ListItem> listItems = new List<ListItem>{firstItem, secondItem, thirdItem};
listItems.sort();
1
  • Thank you so much for your answer!.
    – Rafa H
    Sep 7 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.