Convert List to Set in apex Best Practices

Sometimes, we need to remove duplicates from List type of array. for this, converting list to set is the easy and best way to remove duplicate items.  this is one use case scenario, but any reason if you want to convert list to set, here are two best ways to convert list to set array in apex.

Apex Convert List to Set

Convert list to set using addAll method

// create list and add elements
list<String> testList = list<String>();
testList.add('a');
testList.add('b');
testList.add('a');

// now create set and add list elements to set
Set<String> testSet = Set<String>();
testSet.addAll(testList);

convert list to set using constructor method 

// create list and add elements
list<String> testList = list<String>();
testList.add('a');
testList.add('b');
testList.add('a');

// now create set and add list elements to set
Set<String> testSet = Set<String>(testList);
Labels:
Set
Join the conversation