I have two Lists(Object) List A has 5 records and List b has 19000 records. What i want to do is compare the name field of list a with that of B. it list b consists of the same name as A, then i want to add it to a 3 rd list. I will not be able to use a nested loop because it is exceeding the time limit. is there any way to do this?

1 Answer 1


to avoid nested loops exctract needed names of records to Set. After that iterate listA, and if Set with names contains such name, add that record to listC(third list)

Set<String> listBNames = new Set<String>();
for(Sobject sobj :listB){
List<Sobject> listC = new List<Sobject>();
for(Sobject sobj :listA){
  • I tried using this code after modification listBNames.add((String)sobj.get('Name')); line seems not to be working. it is showing a null list when I print it
    – Rimii
    Jun 23, 2017 at 15:04
  • what is an api name of your "name" field? us it Jun 23, 2017 at 15:14
  • Its standard name so that should work
    – Rimii
    Jun 23, 2017 at 15:20
  • @Rimii i updated my post, can you try it? Jun 23, 2017 at 15:21

You must log in to answer this question.

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