listobjectsalesforceapex-codedistinct-values

Get Unique Values from a list of Objects


Public Class Related Practice{ String Name; Integer id; }

Given a list of 'Related Practice' Objects, I want to extract unique 'Name' values(Distinct values) from the List .

I made an attempt, but it doesn't work for all cases, if anyone has any better ideas ?

//This method return unique values from a list
    private static List<Related_Practice__c> getUniqueValues(List<Related_Practice__c> listInput){
        List<Related_Practice__c> listOutput = new List<Related_Practice__c>();
        
        for(Integer i = 0; i<listInput.size();i++){
            for(Integer j = 0;j<listInput.size();j++){
                if(i != j){
                   if(listInput[j].Practice_Name__c == listInput[i].Practice_Name__c){
                    
                    listInput.remove(j);
                    }
                }
            }
        }
        listOutput.addAll(listInput);
        return listOutput;
    }

`


Solution

  • You can make use of Map instead of using List

    //This method return unique values from a list
        private static List<Related_Practice__c> getUniqueValues(List<Related_Practice__c> listInput){
            
            Map<String,Related_Practice__c> listOutputMap = new Map<String,Related_Practice__c>();
            for(Integer i = 0; i<listInput.size();i++){
                if(!listOutputMap.containsKey(listInput[i].Practice_Name__c)){
                    listOutputMap.put(listInput[i].Practice_Name__c,listInput[i])
                }
               
            }
            
            return listOutputMap.values();
        }