Learn
Sets
Adding and Removing Elements

To add or remove any elements from a set, we must utilize Kotlin’s built-in set functions. Luckily, many of these functions can also be applied to other collection types, thus you might recognize some of these syntaxes from a previous lesson.

To add a single element to a set, we’d use the add() function as we did in the lists lesson; however, if we were interested in adding many elements to a set at once, the addAll() function would be more appropriate. Note that in contrast to lists, we cannot add an element that already exists in the set.

Let’s take a look at how addAll() works. Recall the building example from the previous exercise. The manager got back to us with the following list of apartments:

var aptList = listOf("1A", "1B", "1C", "2A", "2B", "2C", "2C", "1A")

We’re ready to populate our empty set, totalApts, with these values. With the help of the addAll() function, we’re able to populate our set with multiple values at once:

totalApts.addAll(aptList) println(totalApts) // Prints: [1A, 1B, 1C, 2A, 2B, 2C]

Looks like the manager may have accidentally added duplicate apartment numbers. Luckily, the set removed the duplicate elements, and we’re left with unique data.

Oppositely, we can also remove all elements from a collection using the clear() function. Assume the building is selling their property and all of the apartments need to be removed from the data set:

totalApts.clear() println(totalApts) // Prints: []

addAll() and clear() are highly useful, quick, and efficient ways of adding or removing large amounts of data from a collection at once.

Instructions

1.

Codey and his friends want to host a talent show, but before they proceed, they need to ensure that there are at least 5 participants. They’ve gathered the following list of names in TalentShow.kt.

It’s our job to ensure that no name appears twice and that there are enough participants for the show to take place.

First, use the addAll() function to add all of the list names to the uniqueParticipants set at once.

2.

On the following line, use the size property to determine how many participants are in the set. Create the following String template and wrap it in a println() statement:

"The talent show has [setName.size] unique participants."
3.

Great Work! Since there were more than 5 unique participants, the talent show was able to take place, and Codey won for knowing all 88 constellations by heart. ⭐️

Now it’s time to clear all of the participants from the set. On the following line, use the correct function to empty the set.

Use a println() statement to output uniqueParticipants and ensure all values have been cleared.

Folder Icon

Take this course for free

Already have an account?