I have two lists

List<String> lst1 = new List<String>{'a','b','c','d'}; 
List<String> lst2 = new List<String>{'c','d','e','f','g','h'};

I need a list of Strings as below:

List<String> finallist = {'e','f','g','h'};

Compare two lists and remove values present in lst1 of lst2 so I need final list as {'e','f','g','h'} as 'c','d' are present in lst1


You can use Sets for this:

// Given
String[] list1 = new String[] { 'a','b','c','d' };
String[] list2 = new String[] { 'c','d','e','f','g','h' };
// Create a set for list2
Set<String> set1 = new Set<String>(list2);
// Remove anything from list1
// Convert back to list
String[] results = new List<String>(set1);
// Displaying results
System.debug(results); // {'e','f','g','h'}
  • 1 minute for answer O_O – Oleksandr Berehovskyi Jan 13 at 14:28
  • Beat me to it with a better answer, Thanks for showing the usage of removeAll method! – Raul Jan 13 at 14:28
  • @OleksandrBerehovskyi Actually, more like 3 minutes. I misread the question and had to fix my answer. – sfdcfox Jan 13 at 14:30
  • 3
    @Raul You're welcome! I love showing off language features, optimization is one of my favorite hobbies. – sfdcfox Jan 13 at 14:31

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.