1

I'm facing a Requirement Specs that can be simplified to this scenario. Simply put, the specs say to remove all duplicates from a list. This means not to leave one duplicate record from the list but to remove ALL duplicate records.

Example:

List01: a, b, c, d, c, a

Expected Result: List01: b, d

Since a and c were duplicates, they were removed from the list.

I've been struggling on this for quite a while now.

All help is appreciated. Thanks.

  • Add them in the Set – Santanu Boral Nov 21 '18 at 3:28
  • Do you need to keep the original order of the list elements? – David Cheng Nov 21 '18 at 3:46
1

In this case, you can use two sets to find the duplicates:

Set<String> dup1 = new Set<String>(), dup2 = new Set<String>();
for(String item: stringList) {
  if(!dup1.add(item)) { // Have we seen this before?
    dup2.add(item);     // Yes, it's a duplicate
  }
}
Integer index;
for(String dup: dup2) { // For each duplicate
  while((index = stringList.indexOf(dup)) > -1) { // If exists in list
    stringList.remove(index);  // Remove the value
  }
}

If the original list order doesn't matter, you can perform the removals even faster:

Set<String> dup1 = new Set<String>(), dup2 = new Set<String>();
for(String item: stringList) {
  if(!dup1.add(item)) { 
    dup2.add(item);
  }
}
dup1.removeAll(dup2); // Remove all duplicates
stringList.clear();   // Clear original list
StringList.addAll(dup1); // And put the surviving items back in
  • Wow. Thanks for the second answer, it actually works! I actually managed to solve my issue after I posted that question but I used two lists, a nested loop, and an iteration integer. Yours is much simpler and efficient! Thanks! – Jerard Dela Victoria Nov 21 '18 at 7:06
  • @JerardDelaVictoria You're welcome! It might be worth your time to check out the documentation some more; there's a lot of really great methods for Set and Map collections, and knowing how they work can definitely save a lot of time. – sfdcfox Nov 21 '18 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.