遍历列表并删除顶点中的重复项

Iterating Through A List And Removing Duplicate Items in apex

我想从列表中删除基于名称字段的重复条目。 下面是我的代码..

 public class EPM_Contact_Component_Class {
     public List<Hospital_Contacts__c> conList { get; set; }
     public List<Hospital_Contacts__c> result { get; set; }
     public JCT_Hospital_Model__c jctObj { get; set; }
     public Set<Hospital_Contacts__c> myset { get; set; }

 public EPM_Contact_Component_Class(ApexPages.StandardController controller) { }

 public List<Hospital_Contacts__c> getContacts() {
     conList = new List<Hospital_Contacts__c>();
     jctObj = new JCT_Hospital_Model__c();
     jctObj = [Select EPM_Model__r.Name,Hospital__r.Name from JCT_Hospital_Model__c where Id=:ApexPages.currentPage().getParameters().get('Id')];
     system.debug(jctObj.EPM_Model__r.Name);
     conList = [select Contacts__r.Name,Contacts__r.Email,Contacts__r.Phone from Hospital_Contacts__c where EPM_Model__r.Name =: jctObj.EPM_Model__r.Name and Hospital__r.Name=:jctObj.Hospital__r.Name  ORDER BY Contacts__r.Name DESC ];

     myset = new Set<Hospital_Contacts__c>();
     result = new List<Hospital_Contacts__c>();

      for(integer i=0;i<conList.size();i++) {
             Hospital_Contacts__c hospi = conList.get(i);
         for(integer j=(i+1);j<conList.size();j++) {

             Hospital_Contacts__c hospj = conList.get(j); 
             if(hospi.Contacts__r.Name == hospj.Contacts__r.Name) {
                 conList.remove(j); 
                 system.debug('REMOVED::'+j);  
             }
         }
     }
     return conList;
 }

}

重复 2 次时效果很好。当重复次数超过 2 次时,returns 名称重复 2 次。 有人可以帮我吗?

我解决了这个问题。将第二个 For 循环更改为

**for(j=i;j<conList.size();j++)**

将您的内部 for 循环更改为:

for(integer j=0;j<conList.size();j++)

将您的 if 条件更改为:

if(hospi.Contacts__r.Name == hospj.Contacts__r.Name && i!=j)