Set - Methods
Not Started

Most of the instance methods available for sets are the same as those for Lists. The full list is here. Instead of going through all of them, we'll walk through a few highlights.

Sets do not allow duplicates. This means the add() method will work a little differently. An element will not be added to the set if it's already present. Set's add() method returns a Boolean value, indicating whether or not the element was added.

Set<String> usernameSet = new Set<String>(); Boolean wasAdded = usernameSet.add('Caitlin'); // TRUE wasAdded = usernameSet.add('Charlie''); // TRUE wasAdded = usernameSet.add('Caitlin'); // FALSE // usernameSet is {Caitlin, Charlie }

remove() accepts a different parameter than it did with lists. With lists, it accepted an Integer representing the index we wanted to remove. With sets, it accepts the element itself. It will also return a Boolean value indicating whether or not the element was found and removed:

Set<String> usernameSet = new Set<String>(); usernameSet.add('Caitlin'); usernameSet.add('Charlie''); Integer setSize = usernameSet.size(); // 2 usernameSet.remove('Charlie''); // we can choose to ignore the return Boolean didRemoveFrank = usernameSet.remove('Frank'); // FALSE, Frank was never in our set setSize = usernameSet.size(); // 1 // usernameSet is now just { Charlie }

The set collection has a method and overloaded method named retainAll(listOfElementsToRetain) and retainAll(setOfElementsToRetain). These methods can be used to find the intersection of two sets. An intersection is said to be the elements that two sets or lists have in common. If Set1 had values a, b, and c and Set2 had values a and b, the intersection would be a and b because both sets have that value:

Set<String> Set1 = new Set<String>{'a', 'b', 'c'}; Set<String> Set2 = new Set<String>{'a', 'b'}; Set1.retainAll(Set2); // Set1 is now just {'a', 'b'}

Challenge

This version of the removeCountry method accepts two parameters. A set of countries and a country that must be removed. Use the methods from this lesson to remove the country.

Code similar to this may call your code:

Set<String> countrySet = new Set<String>{'Mexico', 'Colombia', 'Argentina', 'Peru'}; CountryController cc = new CountryController(); cc.removeCountry(countrySet, 'Peru');