Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin mutableSetOf()

In Kotlin, sets are collections of elements where each element is unique. mutableSetOf() is a function that lets you create a mutable set, i.e., a set where you can add or remove items after its creation.

Let's dive into mutableSetOf():

Basic Usage:

val colors = mutableSetOf("red", "green", "blue")
println(colors)  // prints [red, green, blue]

Features:

  1. Mutable: As the name suggests, the set returned by mutableSetOf() is mutable. You can add or remove elements.

    colors.add("yellow")
    colors.remove("red")
    println(colors)  // prints [green, blue, yellow]
    
  2. No Duplicates: If you try to add a duplicate value, the set remains unchanged.

    colors.add("green")
    println(colors)  // still prints [green, blue, yellow]
    
  3. Nullable Values: You can create sets that contain nullable elements.

    val nullableSet = mutableSetOf("apple", null, "cherry")
    println(nullableSet)  // prints [apple, null, cherry]
    
  4. Empty Set: You can create an empty mutable set and add elements to it later.

    val emptySet = mutableSetOf<String>()
    emptySet.add("mango")
    println(emptySet)  // prints [mango]
    

Operations on mutableSetOf():

  1. Add Elements: Use add() to add a single element or addAll() to add multiple elements from another collection.

    val fruits = mutableSetOf("apple", "banana")
    fruits.add("cherry")
    fruits.addAll(listOf("kiwi", "orange"))
    println(fruits)  // prints [apple, banana, cherry, kiwi, orange]
    
  2. Remove Elements: Use remove() to remove a single element or removeAll() to remove multiple elements.

    fruits.remove("banana")
    fruits.removeAll(listOf("kiwi", "apple"))
    println(fruits)  // prints [cherry, orange]
    
  3. Check for Elements: Use contains() or the in keyword.

    println("cherry" in fruits)  // prints true
    
  4. Clear the Set: Use clear() to remove all elements.

    fruits.clear()
    println(fruits)  // prints []
    
  5. Iteration: You can iterate over the elements of the set using a for-loop.

    val numbers = mutableSetOf(1, 2, 3)
    for (num in numbers) {
        println(num)
    }
    
  6. Size and Emptiness: Use size to get the number of elements and isEmpty() or isNotEmpty() to check if the set is empty or not.

    println(numbers.size)  // prints 3
    println(numbers.isEmpty())  // prints false
    

In summary, mutableSetOf() provides a way to create and manage mutable sets in Kotlin. Sets are particularly useful when you need to ensure that there are no duplicate elements in the collection. The mutability of mutableSetOf() allows you to modify the set post-creation, offering flexibility in your operations. If you want an immutable set, you can use the setOf() function.

  1. Creating a mutable set in Kotlin with mutableSetOf():

    • Mutable sets can be created using the mutableSetOf() function.
    val numbersSet = mutableSetOf(1, 2, 3, 4, 5)
    
  2. Mutable sets vs immutable sets in Kotlin:

    • Mutable sets, created with mutableSetOf(), allow dynamic addition and removal of elements, unlike immutable sets.
    numbersSet.add(6)
    
  3. Initializing and declaring mutable sets with mutableSetOf() in Kotlin:

    • Mutable sets can be initialized and declared using mutableSetOf() in a single line.
    val namesSet = mutableSetOf("Alice", "Bob", "Charlie")
    
  4. Adding and removing elements in a Kotlin mutable set:

    • Elements can be added using add and removed using remove methods.
    numbersSet.add(7)
    numbersSet.remove(2)
    
  5. Accessing elements in a mutable set created with mutableSetOf():

    • Elements can be accessed through iteration or specific methods.
    val firstElement = numbersSet.first()
    
  6. Iterating over a mutable set in Kotlin:

    • Various loop constructs or collection functions can be used for iteration.
    for (number in numbersSet) {
        // Process each number
    }
    
  7. Filtering and mapping with mutableSetOf() in Kotlin:

    • Functions like filter and map can be used for data transformations.
    val evenNumbers = numbersSet.filter { it % 2 == 0 }
    val squaredNumbers = numbersSet.map { it * it }
    
  8. Mutable set functions and methods in Kotlin:

    • Mutable sets offer various functions and methods for common operations.
    val size = numbersSet.size
    val contains = numbersSet.contains(3)
    
  9. Null safety and mutableSetOf() in Kotlin:

    • Mutable sets can hold nullable types, and null safety principles apply.
    val nullableSet: MutableSet<String?> = mutableSetOf(null, "Hello", null)
    
  10. mutableSetOf() vs setOf() in Kotlin:

    • mutableSetOf() creates mutable sets, while setOf() creates immutable sets.
    val immutableSet = setOf("Alice", "Bob", "Charlie")
    
  11. Using mutableSetOf() with different data types in Kotlin:

    • mutableSetOf() can be used with various data types within the same set.
    val mixedSet = mutableSetOf(1, "Two", 3.0, true)
    
  12. Copying and transforming mutable sets in Kotlin:

    • Mutable sets can be copied or transformed using functions like toSet() and toMutableSet().
    val copySet = numbersSet.toSet()
    val mutableCopySet = numbersSet.toMutableSet()