+ 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>();
// 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

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){

To know more about set :

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
Learn From ver basics how to add values to Apex Collection : List


Happy Learning ☁️⚡️