function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bohemianguy100bohemianguy100 

remove deuplicate and original value from list

I have a list and I need to find if a duplicate value exists in the list and remove both the duplicate value and the original value.

 

I know I can remove the duplicate by using a map or set, but I need to remove the original value as well.

 

For example, if I have a string list:

 

List<String> strings = new List<String>{ 'one', 'two', 'three', 'four', 'one', 'four'};

 

after removing the duplicates and originals I would have:

 

{ 'two', 'three' }

 

Any help is appeciated.

Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
nathaForcenathaForce

Hi boheminanguy100,

 

with a list, I think that you will have to loop twice through it. This is how I would do it.

 

Let me know if this helps...

 

List<String> strings = new List<String>{ 'one', 'two', 'three', 'four', 'one', 'four'}; // this is your original list
Map<String, List<Integer>> counterMap = new Map<String, List<Integer>>(); 
Integer pos = 0;

// 1st loop to identify those items that are duplicates
// We store essentially store the list content in a map ordered by string values, and track the index
for (String stringItem: strings) {
  if (counterMap.get(stringItem) == null) {
    counterMap.put(stringItem, new List<Integer>{pos});
  } else {
    counterMap.get(stringItem).add(pos);
  }
  pos++;
}

// This list will contain the index of all the items to remove
List<Integer> positionsToRemove = new List<Integer>();

// 2nd loop to remove them from the list
// We start from the end of the list because when removing, we want to remove from the end...
for (Integer i=strings.size()-1; i >= 0 ; i--) {
  String stringItem = strings[i];
  // We need at least 2 occurances of the string for it to qualify to be deleted
  if (counterMap.get(stringItem) != null && counterMap.get(stringItem).size() > 1) {
    positionsToRemove.add(i);
  }
}

System.debug('\nRemoving ' + positionsToRemove);

for (Integer indexToRemove: positionsToRemove) {
  strings.remove(indexToRemove);
}

System.debug('\nMy new list: ' + strings);