2

I have a requirement to avoid duplicates entering into the list based on 2 fields Quarter__c and Year__c, Suppose if list already has quarter = 1,Year = 2021 and currency = 'USD', when one more list with same values quarter = 1 and Year = 2021 and currency = 'EUR' entering into the list has to be avoided.

I am not sure how I can approach this since the values are still in the newList and not committed to the database, can anyone please suggest me a way to do this?

public List<Opp_Revenue__c> OppRevenueCreation(Map<Id, Opportunity> OppMap) {
  
    List<Opp_Revenue__c> newList = new List<Opp_Revenue__c>();
    Map<Id, Opportunity> popps = getpopps(OppMap.keySet());

    for (Opportunity opportunity : OppMap.values()) {

        Integer sizeterm = opportunity.size__c.intValue();

        Opportunity previousOpportunity = (Opportunity) popps.get(opportunity.Previous_Opportunity__c);
        Date quarterDate = previousOpportunity.CloseDate;

        for (Integer i = 0; i < sizeterm; i++) {

            newList.add(new Opp_Revenue__c( **// here I have to avoid duplicates based on quarter and Year**
                Opportunity__c = opportunity.Id,
                Quarter__c = getQuarterString(quarterDate),
                Year__c = String.valueOf(getQuarterYearString(quarterDate)),
                CurrencyIsoCode = opportunity.CurrencyIsoCode
            ));

            
        }
    }

    return newList;
}

1 Answer 1

2

This is where sets are useful --

public List<Opp_Revenue__c> OppRevenueCreation(Map<Id, Opportunity> OppMap) {

  Set<Opp_Revenue__c> newOppRevenues = new Set<Opp_Revenue__c>();
  Map<Id, Opportunity> popps = getpopps(OppMap.keySet());

  for (Opportunity opportunity : OppMap.values()) {

    Integer sizeterm = opportunity.size__c.intValue();

    Opportunity previousOpportunity = (Opportunity) popps.get(opportunity.Previous_Opportunity__c);
    Date quarterDate = previousOpportunity.CloseDate;

    for (Integer i = 0; i < sizeterm; i++) {

        newOppRevenues.add(new Opp_Revenue__c( **// here I have to avoid duplicates based on quarter and Year**
            Opportunity__c = opportunity.Id,
            Quarter__c = getQuarterString(quarterDate),
            Year__c = String.valueOf(getQuarterYearString(quarterDate)),
            CurrencyIsoCode = opportunity.CurrencyIsoCode
          ));

        
      }
  }

  return new List<Opp_Revenue__c>(newOppoRevenues);
}
1
  • 1
    Sets can not contain duplicates is what cropredy is saying - so if you put all your intermediate objects into a set, you won't get duplicates. Commented Mar 31, 2021 at 17:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .