Remove duplicate items from a List:
Today I'am going to demonstrate how to remove duplicate values in List. Please add below code in your anonymous window and check how it works.
List<integer> orginalresult=new List<integer>();
orginalresult.add(1); // 0th position
orginalresult.add(2);//1st position
orginalresult.add(2);
orginalresult.add(10);
orginalresult.add(11);
orginalresult.add(3);
orginalresult.add(4);
orginalresult.add(4);
orginalresult.add(1);
orginalresult.add(5);
system.debug('@@@ originalList@@@'+orginalresult);
set<integer> setresult=new set<integer>();
List<integer> Listresult=new List<integer>();
setresult.addAll(orginalresult);
system.debug(setresult);
Listresult.addAll(setresult);
system.debug(Listresult);
Problem: when converted to a Set and then back to a List using addAll(), the order doesn't remain.
Solution:
Solution:
//To maintain order, you need to iterate over the elements:
for(integer s:orginalresult){
if(setresult.add(s)){Listresult.add(s);
}
}
system.debug('@@@ListResult @@@@'+Listresult);
No comments:
Post a Comment