4

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

1 Answer 1

8

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .