Kotlin Set Tutorial 🎯

beginner
5 min

Kotlin Set Tutorial 🎯

Welcome to our comprehensive guide on Kotlin Sets! By the end of this lesson, you'll be well-equipped to understand and apply this powerful data structure in your projects. Let's get started!

What is a Set in Kotlin? 📝

A Set is a collection of unique elements, where each element appears only once. Unlike lists, sets do not maintain the insertion order of elements.

In Kotlin, we have two types of sets:

  1. MutableSet: A set that can be modified after creation.
  2. ImmutableSet: A set that cannot be modified once created.

Creating a Set in Kotlin 💡

Creating a Mutable Set

To create a mutable set, you can use the mutableSetOf() function:

kotlin
val fruits = mutableSetOf("Apple", "Banana", "Mango")

Creating an Immutable Set

To create an immutable set, you can use the setOf() function:

kotlin
val colors = setOf("Red", "Green", "Blue")

Basic Set Operations 💡

Adding Elements

To add an element to a mutable set, use the add() function:

kotlin
fruits.add("Orange")

Removing Elements

To remove an element from a mutable set, use the remove() function:

kotlin
fruits.remove("Banana")

Checking if an Element Exists

To check if an element exists in a set, use the contains() function:

kotlin
println("Banana exists in fruits: ${fruits.contains("Banana")}")

Finding Set Size

To find the size of a set, use the size property:

kotlin
println("Number of fruits: ${fruits.size}")

Set Operations with Multiple Sets 💡

Union

To get the union of two sets, use the union() function:

kotlin
val fruits2 = mutableSetOf("Cherry", "Grape") val allFruits = fruits.union(fruits2)

Intersection

To get the intersection of two sets, use the intersect() function:

kotlin
val commonFruits = fruits.intersect(fruits2)

Difference

To get the difference between two sets, use the minus() function:

kotlin
val fruitsWithoutCherry = fruits.minus("Cherry")

Symmetric Difference

To get the symmetric difference between two sets, use the symmetricDifference() function:

kotlin
val uniqueFruits = fruits.symmetricDifference(fruits2)

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `union()` function do?

By now, you should have a good understanding of sets in Kotlin. Happy coding! 🎉