+ Start a Discussion
Shrey TyagiShrey Tyagi 

Combine 2 lists to make a set - Please help!!!

Hi Everyone,
           Due to some SOQL sub query limitations I have to query list of opportunity records into 2 seperate lists. for our e.g lets call them List A and List B.

So List A gets its values from soql query

List<Opportunity> ListA=[select Id, Name from Opportunity where StageName='Claosed Won'];

List<Opportunity> ListB=[select Id,Name from Oppoortunity where Sub_Stage__c='Aawarded'];

Set<Opportunity> SetC=ListA+ListB.

Now I want to combine List A and List B , take out the duplaicate data out of the combination and make a set out of it  Set c= List A+ List B ( but it should not have any duplaicate records)

Can anyone please help me with the syntax to join 2 lists into a set?

Please note that due to some limits I cannot get all my data into 1 list . The where clause e/g used above are just for theory . It's bit more complicated than that.
Best Answer chosen by Shrey Tyagi
Sure@DreamSure@Dream
Hi Shrey,

You can iterate over the two lists and filter the records based on the "Id". You may need one more set to filter them.
Set<Id> setOfIds = new Set<Id>();
for(Opportunity opp : listA)
{
  SetC.add(opp);
  setOfIds.add(opp.Id);
}

for(Opportunity opp : listB)
{
if( !setOfIds.contains(opp.Id))
{
  SetC.add(opp);
  setOfIds.add(opp.Id);
}
}
Mark this as the solution, if it solves your problem.

Thanks
 

All Answers

Sure@DreamSure@Dream
Hi Shrey,

You can iterate over the two lists and filter the records based on the "Id". You may need one more set to filter them.
Set<Id> setOfIds = new Set<Id>();
for(Opportunity opp : listA)
{
  SetC.add(opp);
  setOfIds.add(opp.Id);
}

for(Opportunity opp : listB)
{
if( !setOfIds.contains(opp.Id))
{
  SetC.add(opp);
  setOfIds.add(opp.Id);
}
}
Mark this as the solution, if it solves your problem.

Thanks
 
This was selected as the best answer
Akhil AnilAkhil Anil
Hi Shrey,

Set has a default uniqueness property which means it will not allow duplicate records to be pushed into the Set. So you can simply add all the elements into the set and it will ensure that only unique records are pushed in. The code would be as below.
 
List<Opportunity> ListA = [select Id, Name from Opportunity where StageName='Claosed Won'];

List<Opportunity> ListB = [select Id,Name from Oppoortunity where Sub_Stage__c='Aawarded'];

Set<Opportunity> SetC = new Set<Opportunity>();

SetC.addAll(ListA);

SetC.addAll(ListB);

Kindly mark it as an answer if that works !