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
ashish jadhav 9ashish jadhav 9 

How can I add list values into set?

Suppose I've a list of fruits like 
List<string> fruits = new List<string> {'mango','papaya','orange','mango'};

then how can I assign this values to set?

for(integer i =0; i<fruits.size(); i++)

set<string> fruits1 = fruits[i];
}

The above code declaration is correct?
Praveen KHariPraveen KHari
List<Integer> ls = new List<Integer>();
ls.add(1);
ls.add(2);
// Create a set based on a list
Set<Integer> s1 = new Set<Integer>(ls);
// Elements are copied from the list to this set
System.debug(s1);// DEBUG|{1, 2}

Above code will help you. More details

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_set.htm#apex_System_Set_ctor
Ajay K DubediAjay K Dubedi
Hi Ashish,
Once you got a List, just iterate it in a for-each loop and use .add method to add the elements in the set. For example you can add the elements of your List "Fruits" to set as :
set<String> setofFruits  = new set<String>();
List<String> fruits = new List<String> {'mango','papaya','orange','mango'};
for(String str :fruits){
setofFruits.add(str);
}

To know more about set :
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_set.htm

Regards,
Ajay
sslodhi87sslodhi87
Hi Ashish,

You can assign the value of list to set by using predefine methods of Set.
List<string> fruits = new List<string> {'mango','papaya','orange','mango'};

Set<String> setFruits = new Set<String>();
setFruits.addAll(fruits );

Please let me know if this helps you!
Ajinkya DhasAjinkya Dhas
Hi,
Learn From ver basics how to add values to Apex Collection : List

https://www.salesforcekid.com/2019/04/salesforce-apex-collection-list.html

Happy Learning ☁️⚡️