ShowAll Questionssorted byDate Posted
jayam

# comparison between two lists

i have two sets with  string values

now  i want to compare the first set to the other and the value which is  there in the second set and not in first set  should be added to   the another list

how can i do this

plz help me

my code is like this

for(integer i=1;i<s1.size();i++)
{
if((city.contains(s1[i]) == false)
}

here s1 and city are sets and lstobj is list object.

JesseA

Think you will need something like below. What it is doing is for each item in list2 it is going through all of list1. If it finds the same value it sets isThisInList1 to true. After going through each value, if our boolean is still false, meaning we didn't find the value in list1 then add it to ValuesNotFoundInList1. Then last before we start with our next list2 value make sure the boolean is false. I apologize for any mistakes, and there is probably a more elegant solution but this should work.

// these are your two lists of strings
List<String> list1;
List<String> list2;
List<String> ValuesNotFoundInList1;
Boolean isThisInList1 = false;
for(Integer i=0; i<list2.size; i++){
for(Integer k=0; k<list1.size; k++){
if(list1[k] == list2[i]){
isThisInList1 = true;
}
}
if(!isThisInList1 ){
}
isThisInList1 = false;
}

sfdcfox

You are indeed trying too elegantly. You can do this:

```List<String> list1 = new List<String>{'test1','test2','test3','test4'};
List<String> list2 = new List<String>{'test1','test3'};
Set<String> set1 = new Set<String>(list1); // Copy the list as a set.
set1.removeAll(list2);  // Remove the items from list2.
system.debug(set1);  // Set1 contains {'test2','test4'}```

No need to do loops or anything fancy. You can iterate through the set in a for loop, or copy it back into a list when you're done. Either way, the platform already has the logic you need to quickly and easily determine which items in the list do not belong.

JesseA

Slick.

jayam

but

the first list is sobject type ,it contains the list of names

and the second list is string type

when i compare those two, error came

what can i do?

sfdcfox

```// firstList is List<Sobject>
// secondList is List<String> or Set<String>

// Store temporary copy of records
Map<String,SObject> nameMap = new Map<String,Sobject>();
// Create map from name to sobject
for(Sobject record:firstList)
nameMap.put(record.get('name'),record);
// Remove entries from map's keys
nameMap.keyset().removeAll(secondList);
// values() returns List<Sobject> with items left.
System.debug(nameMap.values());
```

You might need to tweak this code to suit your specific scenario, but I believe that a Map should be able to accomplish your goals in a similar fashion as the previous example; SObjects are complex objects, and so you have to map them to a simple type if you want to compare them quickly using the methods available to sets.