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
Ranu JainRanu Jain 

sorting on sObject

i want to sort sObjects when click on an image

 

either  i  call a method  for soritng or i  i can fire a DML query ?

which method wud be most preferable in salesforce?

 

*i have to sort list of products in opportunity

 

kiranmutturukiranmutturu

if you can do this through query then obviously this is the best way.. if you have list of values which are not returned through query then u need to go with custom logic....

Ranu JainRanu Jain

Thanks

                                      i am very new in salesforce ..we are asked to fire minium query because of governors limits in salesforce. then also  ur suggested method is better?

 

and one more thing can i get map by firing dynamic query?

i mean....

maps=new Map<id,Product>[query ]

 

in the [ ]  i want to write dynamic query which usualy possible by database.query()?   is it possible to get map any how?


Chamil MadusankaChamil Madusanka

Use this class for sort sObject.

 

//This class will help to Sort List<sObject>
public class ListSortHelper  {     // <ID, Position>
    private Map<String, Integer> listPosition = null;    // <FieldName, <FieldValues>>
    private Map<String, List<String>> sortedFieldValuesPerFieldName = null;     // <FieldName, <FieldValue, <IDs>>>
    private Map<String, Map<String, List<String>>> sObjectIDsPerFieldNames = null;
    
// Properties
    public List<sObject> originalList {get; set;}
    public String DataType {get; set;}
    
// Constructor
    public ListSortHelper() {
        originalList = null;
    }// Public Method
    public List<sObject> getSortedList(String fieldName, Boolean ascending) {
        if (originalList == null) {
            // Assume that originalList has a not NULL value.
            // If the class who uses this method has not assigned a value it will get an Exception which
            //    needs to be handled by the calling class.            // Force the exception...
            originalList.clear();
        }        // Make field name uppercase
        fieldName = fieldName.toUpperCase();        // Get sorted list
        return makeSortedList(fieldName, ascending);
    }
    public List<sObject> getSortedList(List<sObject> originalList, String fieldName, Boolean ascending) {
        this.originalList = originalList;
        sortedFieldValuesPerFieldName = null;
        return getSortedList(fieldName, ascending);
    }
    
// Private Methods
    private void InitializeFieldName(String fieldName) {
        String sObjectID;
        Integer position;
        String fieldValue;
        List<String> sObjectIDs = null;
        Set<String> valuesForFieldSet = null;    // Sets automatically omit duplicate values 
        List<String> valuesForFieldList = null;
       
        List<Decimal> valuesForFieldListDecimal = null;  
        List<Integer> valuesForFieldListInteger = null; 
        
       
        
        Map<String, List<String>> sObjectIDsPerFieldValues = null;
        
        // Make sortedFieldValuesPerFieldName
        if (sortedFieldValuesPerFieldName == null) {
            listPosition = new Map<String, Integer>();
            sortedFieldValuesPerFieldName = new Map<String, List<String>>();
            sObjectIDsPerFieldNames = new Map<String, Map<String, List<String>>>();
        }
        
        // Get (or create) map of sObjectIDsPerFieldValues
        sObjectIDsPerFieldValues = sObjectIDsPerFieldNames.get(fieldName);
        if (sObjectIDsPerFieldValues == null) {
            sObjectIDsPerFieldValues = new Map<String, List<String>>();
            sObjectIDsPerFieldNames.put(fieldName, sObjectIDsPerFieldValues);
        }
        if (!sortedFieldValuesPerFieldName.keySet().contains(fieldName)) {
            // Objects need to be initialized
            position = 0;
            valuesForFieldSet = new Set<String>();
            listPosition = new Map<String, Integer>();
           
            for (sObject sObj : originalList) {
             System.Debug('sObj :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::'+sObj );
                sObjectID = sObj.ID;
                
                    fieldValue = getValue(sObj, fieldName);
                
                
                // Add position to list
                listPosition.put(sObjectID, position++);
                
                // Add the value to the set (sets rather than lists to prevent duplicates)
                valuesForFieldSet.add(fieldValue);
                
                // Get (or create) map of sObjectIDs
                sObjectIDs = sObjectIDsPerFieldValues.get(fieldValue);
                if (sObjectIDs == null) {
                    sObjectIDs = new List<String>();
                    sObjectIDsPerFieldValues.put(fieldValue, sObjectIDs);
                }
                
                // Add ID to sObjectIDs
                sObjectIDs.add(sObjectID);
            }
            
            // Sort set items (Need to convert to list)
            valuesForFieldList = new List<String>();            
            valuesForFieldList.addAll(valuesForFieldSet);
            
            if(DataType == 'Decimal')
            {
                valuesForFieldListDecimal = new List<Decimal>(); 
                for(String strValue : valuesForFieldList)
                {
                    if(strValue == null)
                    {
                        strValue='0.0';
                    }
                    valuesForFieldListDecimal.add(Decimal.valueOf(strValue));
                }
                valuesForFieldListDecimal.sort();   
                valuesForFieldList.clear();
                for(Decimal decValue : valuesForFieldListDecimal)
                {
                    valuesForFieldList.add(String.valueOf(decValue));
                }  
            } //
            else if(DataType == 'Integer')
            {
                valuesForFieldListInteger = new List<Integer>(); 

                for(String strValue : valuesForFieldList)
                {
                    valuesForFieldListInteger.add(Integer.valueOf(strValue));
                }
                valuesForFieldListInteger.sort();   
                valuesForFieldList.clear();
                for(Integer intValue : valuesForFieldListInteger)
                {
                    valuesForFieldList.add(String.valueOf(intValue));
                }  
            }
            else
            {
                valuesForFieldList.sort(); 
            }                   
                    
            
            
            
            // Now add it to the map.
            sortedFieldValuesPerFieldName.put(fieldName, valuesForFieldList);
        }
    }
    private List<sObject> makeSortedList(String fieldName, Boolean ascending) {
        Integer position;
        List<String> sObjectIDs = null;
        List<String> valuesForFieldList = null;        // Initialize objects
        InitializeFieldName(fieldName);        // Get a list of the same type as the "originalList"
        List<sObject> outputList = originalList.clone();
        outputList.clear();        // Get a list of sorted values
        valuesForFieldList = sortedFieldValuesPerFieldName.get(fieldName);
        
        // for each sorted value
        for (String fieldValue : valuesForFieldList) {
            // Get lisft of IDs
            sObjectIDs = sObjectIDsPerFieldNames.get(fieldName).get(fieldValue);
            
            // for each ID
            for (String ID : sObjectIDs) {
                // Get position in originalList
                position = listPosition.get(ID);                // Add each sObject to the list.
                if ((ascending) || (outputList.size()==0)) {
                    outputList.add(originalList[position]);
                } else {
                    outputList.add(0, originalList[position]);
                }
            }
        }
        return outputList;
    }
    private static String getValue(sObject sObj, String fieldName) {
        // This returns the sObject desired in case the fieldName refers to a linked object.
        Integer pieceCount;
        String[] fieldNamePieces;
        
        fieldNamePieces = fieldName.split('\\.');
        pieceCount = fieldNamePieces.size();
        for (Integer i = 0; i < (pieceCount-1); i++) {
            sObj = sObj.getSObject(fieldNamePieces[i]);
        }
        return String.valueOf(sObj.get(fieldNamePieces[pieceCount-1]));
    }
    
// Unit testing
/*
    static testMethod void testSortCustomObject() {
        List<TPValue__c> TPValues;
        ListSortHelper sorter = new ListSortHelper();
        String fieldName;
        
        TPValues = [SELECT TPName__r.TPName__c, Value__c FROM TPValue__c LIMIT 50];
        fieldName = 'Value__c';
        testOrderedList(sorter.getSortedList(TPValues, fieldName, true), fieldName, true);
        
        fieldName = 'TPName__r.TPName__c';
        testOrderedList(sorter.getSortedList(TPValues, fieldName, true), fieldName, true);
    }
*/
    static testMethod void testSimpleField_Ascending() {
        testSortingContacts('Name', true);
    }
    static testMethod void testSimpleField_Descending() {
        testSortingContacts('Name', False);
    }
    static testMethod void testLookupField_Ascending() {
       // testSortingContacts('Account.Name', True);
    }
    static testMethod void testLookupField_Decending() {
       // testSortingContacts('Account.Name', False); 
    }
    static testMethod void testMultipleCalls() {
        ListSortHelper sorter;
        sorter = testSortingContacts(null, 'Name', true);
        testSortingContacts(sorter, 'Name', False);
       // testSortingContacts(sorter, 'Account.Name', True);
       // testSortingContacts(sorter, 'Account.Name', False);
    }
    static testMethod void testForgotOriginalList() {
        Boolean exceptionDetected = false;
        ListSortHelper sorter = new ListSortHelper();
        try {
            sorter.getSortedList('Name', true);
        } catch (NullPointerException e) {
            exceptionDetected = true;
        }
        System.assert(exceptionDetected);
    }
    static testMethod void testPassingList() {
        ListSortHelper sorter = new ListSortHelper();
        List<Contact> contacts = [SELECT Name, Phone, Account.Name FROM Contact LIMIT 50];
        List<Contact> sortedList = (List<Contact>) sorter.getSortedList(contacts, 'Name', true);
        
            testOrderedList(sortedList, 'Name', true);
        
    }
    private static void testSortingContacts(string fieldName, Boolean isAscending) {
        testSortingContacts(null, fieldName, isAscending);
    }
    private static ListSortHelper testSortingContacts(ListSortHelper sorter, string fieldName, Boolean isAscending) {
        // If sorted is null,create it.        
        if (sorter == null) {
            sorter = new ListSortHelper();
            sorter.originalList = [SELECT Name, Phone, Account.Name FROM Contact LIMIT 50];
        }
        
        // Sort list
        List<Contact> sortedList = (List<Contact>) sorter.getSortedList(fieldName, isAscending);        // Test sort order
        testOrderedList(sortedList, fieldName, isAscending);
        
        return sorter;        
    }
    private static void testOrderedList(List<sObject> sortedList, string fieldName, Boolean isAscending) {
        String lastValue = null;
        String currentValue = null;        
        for (sObject sObj : sortedList) {
        if(sObj != null)
        {
            currentValue = getValue(sObj, fieldName);
            if ((lastValue != null) && (currentValue != null)) {                String strDebug = '';
                strDebug += '\n--------------------------------------------------------------';
                strDebug += '\nSTART';
                strDebug += '\n--------------------------------------------------------------';
                strDebug += '\n[Ascending:'+isAscending+']';
                strDebug += '\n[Previous:'+lastValue+'] [IsNull():'+(lastValue==null)+']';
                strDebug += '\n[Current:'+currentValue+'] [IsNull():'+(currentValue==null)+']';
                strDebug += '\n[CompareTo:'+(currentValue.compareTo(lastValue))+']';
                strDebug += '\n--------------------------------------------------------------';
                strDebug += '\nEND';
                strDebug += '\n--------------------------------------------------------------';
                System.debug(strDebug);                if (isAscending) {
                    System.assertEquals(currentValue.compareTo(lastValue)>=0, true);
                } else {
                    System.assertEquals(currentValue.compareTo(lastValue)<=0, true);
                }
            }
            lastValue = currentValue;
            }
        }
    }    
    
}

 Assign your oSbject list to the "originalList" property of ListSortHelper class. Then call the getSortedList(String fieldName, Boolean ascending) method. Then you will get the sorted list .

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

EJWEJW

Ranu Jain wrote:

Thanks

                                      i am very new in salesforce ..we are asked to fire minium query because of governors limits in salesforce. then also  ur suggested method is better?

 

and one more thing can i get map by firing dynamic query?

i mean....

maps=new Map<id,Product>[query ]

 

in the [ ]  i want to write dynamic query which usualy possible by database.query()?   is it possible to get map any how?



Creating a map<Id, sObject> from a list of sObjects will automatically create a map keyed by Id.  However, in the past the map had to be strongly typed, I'm not sure this limitation still exists.  For example, this should work:

 

Map<Id, Product> products = new Map<Id, Product>( Database.query( 'SELECT Id FROM Product WHERE Name LIKE \'' + nameParam + '%\'' ) );

DrBixDrBix

You could also use apex-lang.  I generally try to keep to sorting in my Query, but apex-lang can sort SObjects I believe.

 

http://code.google.com/p/apex-lang/