2

I have two list T1 and T2 , T1 has 5 records and T2 has 10 records... now i want to add t1 in another list t3 if the id doesnt exist in t3 .

Need little help in achieving this in apex

  • More information please, also post what code you've tried so far. – Davin Casey Jun 17 '14 at 13:58
3

If you convert the List to a Set you can use the contains(Object) function and just iterate over the other list elements to find which ones are missing from the set and then just add them to the list t3.

To get a Set from a List you can use the constructor new Set<T>(List<T>)

You could try something like the following where T is the type of your record (I'm assuming that you meant "if the id doesn't exist in t2" rather than "if the id doesn't exist in t3" in your question):

List<T> t1 = ...
List<T> t2 = ...
List<T> t3 = ...

Set<T> s2 = new Set<T>(t2);
for(T t : t1) {
    if(!s2.contains(t)) {
        t3.add(t);
    }
}
  • 1
    Note that if T is an SObject, all the fields are considered not just the ID field which may or may not be what is wanted. – Keith C Jun 17 '14 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.