Introduction

Welcome to our exploration of Kotlin Sets! Sets in Kotlin are collections that hold only distinct values, ensuring that no element appears more than once. They are ideal when uniqueness is a requirement within your data collection.

In this lesson, you'll gain knowledge of creating and working with sets in Kotlin. This includes understanding both immutable and mutable sets and how sets improve performance in specific operations. Let's get started!

Creating and Manipulating Sets

In Kotlin, you can create sets using setOf() for immutable sets and mutableSetOf() for sets that can change.

// Creating immutable and mutable sets
fun main() {
  val mySet = setOf(1, 2, 3, 4, 5, 5, 5)  // Duplicates are automatically removed
  val myMutableSet = mutableSetOf(1, 2, 3, 4, 5, 5, 5)  // Similar behavior for mutable sets

  println(mySet)  // Output: [1, 2, 3, 4, 5]
  println(myMutableSet) // Output: [1, 2, 3, 4, 5]
}

Kotlin provides various functions to manipulate these sets. Particularly for MutableSet, functions such as add(), remove(), and contains() are available:

fun main() {
    val myMutableSet = mutableSetOf(1, 2, 3, 4, 5)

    // Adding an element
    myMutableSet.add(6)  // `myMutableSet` is now [1, 2, 3, 4, 5, 6]

    println(myMutableSet.contains(1)) // Output: true, as `myMutableSet` includes an element 1

    // Removing an element
    myMutableSet.remove(1)  // `myMutableSet` becomes [2, 3, 4, 5, 6]

    println(myMutableSet.contains(1)) // Output: false, as `myMutableSet` doesn't include 1 anymore

    // Discarding an element (safe removal)
    myMutableSet.remove(7)  // No changes - 7 doesn't exist in `myMutableSet`
}
  • add(): Adds an element to the MutableSet. If the element is already present, the set remains unchanged.
  • contains(): Checks if a specific element is present in the set, returning true or false.
  • remove(): Removes an element from the MutableSet; if the element isn't present, the set remains unchanged, indicating safe removal.
Set Operations

Kotlin has built-in operations for sets such as union(), intersect(), and subtract(), which can be utilized both as functions and operators.

fun main() {
    val set1 = setOf(1, 2, 3, 4)
    val set2 = setOf(3, 4, 5, 6)

    // Set union
    println(set1 union set2)
    // Output: [1, 2, 3, 4, 5, 6]

    // Set intersection
    println(set1 intersect set2)
    // Output: [3, 4]

    // Set difference
    println(set1 subtract set2)
    // Output: [1, 2]
}
  • union(): Combines elements from both sets without duplicates, resulting in {1, 2, 3, 4, 5, 6} for set1 union set2.
  • intersect(): Outputs elements found in both sets, leading to {3, 4} in this example.
  • subtract(): Results in the unique elements from the first set, yielding {1, 2} for set1 subtract set2.
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal