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
Rajeev SatapathyRajeev Satapathy 

Compare two list in Apex

I want to compare two list in which values are stored in a different order . I am inserting the list into different maps . how to compare that the data in list 1 is present in list 2.
Best Answer chosen by Rajeev Satapathy
Frédéric TrébuchetFrédéric Trébuchet
Hi,

As you cannot directly sort a map, you have to search each member of list1 in list2.
Also you can copy the desired data from your maps to lists which then can be sorted using sort method.
After that, you can search for each list1 members in list2 using contains method.

Hope this helps,
Fred

All Answers

Frédéric TrébuchetFrédéric Trébuchet
Hi,

As you cannot directly sort a map, you have to search each member of list1 in list2.
Also you can copy the desired data from your maps to lists which then can be sorted using sort method.
After that, you can search for each list1 members in list2 using contains method.

Hope this helps,
Fred
This was selected as the best answer
Frédéric TrébuchetFrédéric Trébuchet
If this answer helped you solve your problem, please, mark the question as Solved and kindly select the best answer ;)

Thanks,
Fred
YuchenYuchen
If you only want to find out what data in list 1 is present in list 2, I think you can try the folloing:

First, convert these two list to Set. You can use "Set<String> theSet = new Set<String>(theList);" to do this.

Second, loop through the new Set 1, check whether that individual value is contained in Set 2 using "theSet2.contains(X)"
Frédéric TrébuchetFrédéric Trébuchet
Using sorted lists may allow you to finish faster cause you don't have to scan all list2 members - as soon reached value is greater than current value from list1 you can say lists are differents