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
BPOORBPOOR 

combine two lists with different fields into one list

I have two lists with two different different fields to update the asset object in Salesforce. Below is the sample data.
 
List1:
====

AssetId                      Field1
a2i1                           abc
a2i2                           acb
a2i3                           cad
a2i4                           gfd


List2:
====

AssetId                      Field2
a2i0                           mnp
a2i2                           nop
a2i3                           mnh
a2i7                           pqr
a2i8                           iyo


Expected Output List:
==================

AssetId                      Field1             Field2
a2i0                                                  mnp
a2i1                           abc
a2i2                           acb                 nop
a2i3                           cad                 mnh
a2i4                           gfd
a2i7                                                   pqr
a2i8                                                   iyo

When I merge them into one list, I get an exception during the update as the list has duplicate ids in it (a2i2, a2i3). I would like to merge both lists into one, but having both fields in the list as shown above.

Since the lists contain Ids, I can convert them into two maps and loop thru the first map using KeySet() and check if the Id is present in the second map. If it is available, I can populate field2. But I need to repeat the same with map2.

Is there a better approach for this?
 
Shubham Jain 338Shubham Jain 338
Hi,

You can create a map like MAP<Id, NAME_OF_OBJECT> then iterate over both the list and check if the map contains id then use the instance and if not then add the instance.

Please mark this as the best answer if it helps.

Thanks
Shubham Jain
 
BPOORBPOOR
This is the solution I have in mind. I am looking for any other better approach instead of looping thru two maps.
Shubham Jain 338Shubham Jain 338
Hi,
There will be only one map, you will have to iterate both the list or combine both the list and iterate. The TC will be 0(n) only.
If you can post your code here so that I can look and see what you have done and will try to optimize it.

Thanks
Shubham Jain