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
Kishore DasariKishore Dasari 

How to use addAll() method in For loop?

I want to use addAll() instead of add() in below code. How to achieve this?
//one list is there: myList1
List<String> myList1 = New List<String>;

//I want to add Name field values from my Custom Meta Data to myList
for(myCustomMetaData__mdt mtdVar: [select id, Name from myCustomMetaData__mdt LIMIT 1000]){
            myList1.add(mtdVar.Name);
        }
Khan AnasKhan Anas (Salesforce Developers) 
Hi Kishore,

Greetings to you!

add() is used in List when you wish to add ONE element to the end of the list.
 
addAll() is used when you wish to add contents of an already existing List to a List. Both lists must be of the same type.
 
//First List: myList1
List<String> myList1 = New List<String>;

for(myCustomMetaData__mdt mtdVar1: [SELECT Id, Name FROM myCustomMetaData__mdt LIMIT 1000]){
            myList1.add(mtdVar.Name);
}

//Second List: myList2
List<String> myList2 = New List<String>;

for(myCustomMetaData__mdt mtdVar2: [SELECT Id, Name FROM myCustomMetaData__mdt WHERE Name IN ('test1','test2','test3')]){
            myList2.add(mtdVar.Name);
}

// Add Add all elements from list – myList1 to myList2
myList2.addAll(myList1);

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Bharath CTSBharath CTS


You can do as below: 

List<String> myList1 = New List<String>;
List<String> myList2 = New List<String>;

for(myCustomMetaData__mdt mtdVar: [select id, Name from myCustomMetaData__mdt LIMIT 1000]){
            myList1.add(mtdVar.Name);
        }

myList2 .addAll(myList1); //Adding list to list