+ Start a Discussion
bprakashbprakash 

Difference between sets

How can i get the difference of two sets?

Set<Id> A,Set<Id>B

 

i need to find difference between A & B

 

PLease suggest on this

 

Thanks

JitendraJitendra

Hi,

Please find below code snippet:

 

Set<String> seta = new String<String>();
seta.add('a');
seta.add('b');
seta.add('c');



Set<String> setb = new String<String>();
setb.add('b');
setb.add('c');
setb.add('d');


if(seta.size() > setb.size())
{
	//Set a has more element and NOT same
}else if(seta.size() < setb.size())
{
	//Set b has more element
}else
{
	//Number of element are same
	setb.removeAll(seta);
	if(setb.size() == 0)
	{
		//both are same
	}
	else
	{
		//both are not same
	}
}

 

 

bprakashbprakash

Thanks for the reply

Iam sorry i had actually Lists A and B which stores the values of strings,

assue A ---> '1','2';

 

            B------> '1','2','3';

 

I want the value 3,(.e difference in the elements)

 

Please guide me how can i go for this

 

Thanks

 

SamuelDeRyckeSamuelDeRycke

Did you look at the Set Methods documentation ?

 

You could do something iterative, or you could do some smart method utilization. Assuming you want unique elemets from both lists, and not only from list B :

 

Set<String> seta = new Set<String>();
seta.add('a');
seta.add('b');
seta.add('c');

Set<String> setb = new Set<String>();
setb.add('b');
setb.add('c');
setb.add('d');

Set<String> result = seta.clone();
result.removeall(setb);
setb.removeall(seta);

result.addall(setb);

system.debug('--------------------------->'+result);

//output : |USER_DEBUG|[18]|DEBUG|--------------------------->{a, d}