Lesson 4

Discovering the Uniqueness within Collections: Working with Sets in Kotlin

Topic Overview and Actualization

In today's lesson, we're going to dive into an important Kotlin data structure: Sets. A Set, just as it is in mathematics, is a collection of distinct elements, meaning it cannot contain duplicate values. They are useful in many scenarios, such as when you want to keep a record of unique items. For instance, imagine you have a list of books in a library, and you want to know the available different genres without going through the same genre multiple times. A Set would be the preferred data structure for such a case.

In this lesson, we'll learn how to create Sets, manage their elements, and utilize their properties. Combined with what we've already learned about Arrays and Lists, this knowledge will empower you with a strong understanding of Kotlin data structures.

Introduction to Sets in Kotlin

Sets are one of the data structures provided by Kotlin for storing different types of data, akin to Arrays and Lists. However, in contrast to Arrays and Lists, Sets hold unique elements, meaning no two elements in a Set can be identical. This uniqueness property of a Set makes it ideal for use when you want to avoid storing duplicate data.

Imagine you're running a unique email drawing competition where everyone with an email is allowed to participate once. A Kotlin Set would be the perfect container for the emails because it would ensure each email is listed only once.

Having said that, you must remember that a Set will not keep track of the order in which elements were inserted. So always remember this when dealing with Sets: the order doesn't matter, and each element is unique!

Creating and Managing Sets in Kotlin

Creating Sets in Kotlin is a breeze. Kotlin offers us the setOf() function to create an immutable Set and the mutableSetOf() function to create a mutable Set. Immutable sets cannot be modified after creation, while mutable sets allow changes. Here's how you can create sets:

Kotlin
1fun main() { 2 // Creating an immutable Set 3 val numbers = setOf("one", "two", "three") // This set cannot be modified 4 println("Immutable set: $numbers") // Prints "Immutable set: [one, two, three]" 5 6 // Creating a mutable Set 7 val mutableNumbers = mutableSetOf("one", "two", "three") 8 9 // Changing mutable Set 10 mutableNumbers.add("four") // Adds "four" into mutableNumbers 11 mutableNumbers.add("four") // Adds "four" into mutableNumbers again 12 mutableNumbers.remove("one") // Removes "one" from mutableNumbers 13 14 println("Mutable set after changes: $mutableNumbers") // Prints "Mutable set after changes: [two, three, four]", note that the order is not guaranteed 15}

Here, we've also shown how to add and remove elements from mutable sets using the add() and remove() functions, respectively.

Accessing Elements of a Set

Because a Set doesn't maintain an order, indexing does not work when trying to access elements of a Set. However, Kotlin makes it very easy to check if an item exists within a Set using the in operator. Given a Set animals that contains various animals, if we wanted to check if "lion" is one of the animals, we would do it like this:

Kotlin
1// Kotlin main function 2fun main() { 3 val animals = setOf("tiger", "lion", "monkey") 4 5 // Checking if lion is in the Set 6 if ("lion" in animals) { 7 println("Lion is in the animal kingdom!") 8 } 9}

If this code is run, it will print "Lion is in the animal kingdom!" because "lion" is indeed in our Set animals.

Properties of Sets

Just like Arrays and Lists, Sets also come with built-in properties that provide helpful information about our Set.

The size property returns the number of elements in the Set. Continuing with our animals Set from the previous example, animals.size would return 3 because our Set has three elements: "tiger", "lion", and "monkey".

Another property of interest is isEmpty(), which checks if a Set is empty or not.

Kotlin
1// Kotlin main function 2fun main() { 3 val animals = setOf("tiger", "lion", "monkey") 4 5 println("The number of animals is: ${animals.size}") 6 println("Is the set empty? Answer: ${animals.isEmpty()}") 7}

If you run this code, it will print that the number of animals is 3 and that the set is not empty.

Lesson Summary and Practice

There you have it! Working with Sets in Kotlin doesn't need to be a daunting task. You can create Sets, manage their elements (add and remove, in case of mutable Sets), check if an item exists in a Set, and use properties like size and isEmpty() to glean important information from a Set. Not only should you now understand how Sets work in Kotlin, but you should also know where they can be most effectively applied.

Now, it's time for some hands-on practice with Sets to solidify what you've just learned. These exercises will help you hone your Kotlin skills and build a solid foundation that we will continue to build on in the next lessons. And remember, practice makes perfect, especially when learning a programming language!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.