1. You can make a query using the order by keyword and assign the result to the list
- If the list is formed already, then you can take the record Ids from that list into a set and in the query mention "where Id IN : set AND order by Name/..."
2. you can add the records into a map. The map should be like : key as the Field (on which field basis you want to sort) and the value is SObject
- Now the map is formed and the keyset of the map can be sorted . When keys are sorted obviously the values also will get sorted.
global class Book implements Comparable {
public String BookTitle ;
public String Author ;
public Integer TotalPages ;
public Double Price ;
public Date publishingDate;
public enum SORT_BY {
ByTitle,ByPage
}
//Variable to decide the member on which sorting should be performed
public static SORT_BY sortBy = SORT_BY.ByTitle;
public Book(String bt, String a, Integer tp, Double p, Date pd)
{
BookTitle = bt;
Author = a;
TotalPages = tp;
Price = p;
publishingDate = pd;
}
global Integer compareTo(Object objToCompare) {
//Sort by BookName Alphabetically
if(sortBy == SORT_BY.ByTitle)
{
return BookTitle.compareTo(((Book)objToCompare).BookTitle);
}
else //Sort by Book price
{
return Integer.valueOf(Price - ((Book)objToCompare).Price);
}
}
}
Book[] books = new Book[]{
new Book('Salesforce Handbook','Jeff Douglas',360,35,Date.newInstance(2011, 03, 20)),
new Book('Let Us C','Yashavant P. Kanetkar',593,58,Date.newInstance(2008, 03, 21)),
new Book('Head First Design Patterns ','Elisabeth Freeman',678,28,Date.newInstance(2004, 11,01))
};
Book.sortBy = Book.SORT_BY.ByTitle;
books.sort();
System.debug(books);
Book.sortBy = Book.SORT_BY.ByPrice;
books.sort();
System.debug(books);
1. You can make a query using the order by keyword and assign the result to the list
- If the list is formed already, then you can take the record Ids from that list into a set and in the query mention "where Id IN : set AND order by Name/..."
2. you can add the records into a map. The map should be like : key as the Field (on which field basis you want to sort) and the value is SObject
- Now the map is formed and the keyset of the map can be sorted . When keys are sorted obviously the values also will get sorted.
- Now take the map values into a list.
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_orderby.htm
Option 2:- How to Sort Wrapper class Collection in Apex
http://www.jitendrazaa.com/blog/salesforce/how-to-sort-wrapper-class-collection-in-apex/ Please let us know if this will help u
Thanks
\Amit Chaudhary