+ Start a Discussion
subbu123.pbt@gmail.comsubbu123.pbt@gmail.com 

display the duplicate values present in a list.

List   li=new List();

li.add("12");

li.add("13");

li.add("14");

li.add("12");

li.add("14");

 

My Requirment  Is Display only Duplicate values like 12 , 14 values ,  what i  do ?

ple guide me , how to do .    thank u in advanced.

 

 

 

 

devnextdoordevnextdoor

Hi,

 

You can try this:

 

List   li=new List();

li.add("12");

li.add("13");

li.add("14");

li.add("12");

li.add("14");

 

Set set = new Set();

List duplicateList = new List();

 

for(String s: li) //assuming the data is String

{

if(set.contains(s){

duplicateList.add(s)

}else{

set.add(s);

}

}

 

//print duplicate list from duplicateList variable.

 

regards,

 

amarcuteamarcute

Hi,

 

Try this out:

 

List<String> li = new List<String>();
li.add('12');
li.add('13');
li.add('14');
li.add('12');
li.add('14');
Set<String> myset = new Set<String>(); List<String> result = new List<String>(); for (String s : li) { if (myset.add(s)) { result.add(s); } } System.debug(LoggingLevel.INFO, 'result: '+result);

 Set.add() returns a Boolean, which is true if it was successfully added to the set.  If the object was already in the set, it will be false.

 

 

amarcuteamarcute

Oh...The code above removes the duplicates, but if you want to retain the duplicates, use the bellow code:

 

List<String> li=new List<String>();
li.add('12');
li.add('13');
li.add('14');
li.add('12');
li.add('14');
 
Set<String> mySet = new Set<String>();
List<String> duplicateList = new List<String>();
 
for(String s: li) //assuming the data is String
{
  if(mySet.contains(s)){
    duplicateList.add(s);
  }else{
    mySet.add(s);
  }
}
System.debug(LoggingLevel.INFO, 'duplicateList: '+duplicateList);