Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Set : setOf()

In Kotlin, a Set is a collection that doesn't allow duplicate elements. The setOf() function is used to create an immutable set of elements. This means that once a set is created using setOf(), you cannot add or remove elements from it.

Basic Usage:

  1. Creating a Set:

    To create a set of elements, you can use the setOf() function:

    val numbers = setOf(1, 2, 3, 4, 5)
    val names = setOf("Alice", "Bob", "Charlie")
    
  2. Duplicate Elements:

    If you try to create a set with duplicate elements, the duplicates will be ignored:

    val numbersWithDuplicates = setOf(1, 2, 2, 3, 3, 4, 5)
    println(numbersWithDuplicates)  // Outputs: [1, 2, 3, 4, 5]
    
  3. Accessing Elements:

    You can use standard collection functions to access elements or check for their existence:

    if (3 in numbers) {
        println("3 is in the set")
    }
    
    for (name in names) {
        println(name)
    }
    
  4. Immutable Nature:

    Remember that the set created with setOf() is immutable. This means you can't add or remove elements:

    // This will cause a compile-time error:
    // numbers.add(6)
    

Common Operations:

  1. Size:

    To get the number of elements in the set:

    println(numbers.size)  // Outputs: 5
    
  2. Checking for an Element:

    To check if an element exists in the set:

    println(2 in numbers)  // Outputs: true
    
  3. Union, Intersection, and Difference:

    You can perform basic set operations:

    val set1 = setOf(1, 2, 3, 4)
    val set2 = setOf(3, 4, 5, 6)
    
    println(set1 union set2)         // Outputs: [1, 2, 3, 4, 5, 6]
    println(set1 intersect set2)     // Outputs: [3, 4]
    println(set1 subtract set2)      // Outputs: [1, 2]
    
  4. Empty Sets:

    If you want to create an empty set:

    val emptySet = setOf<String>()
    

Conclusion:

The setOf() function in Kotlin is a convenient way to create immutable sets of elements. If you need a mutable set, you can use mutableSetOf(), which returns a MutableSet that you can modify. When working with sets, you can make use of standard collection functions and set-specific operations like union, intersection, and subtraction.

  1. Creating a set in Kotlin with setOf():

    • Use the setOf() function to create an immutable set.
    val mySet = setOf("apple", "banana", "orange")
    
  2. Immutable sets in Kotlin:

    • Sets created with setOf() are immutable and cannot be modified.
    val immutableSet = setOf("one", "two", "three")
    
  3. Initializing and declaring sets with setOf() in Kotlin:

    • Initialize and declare a set using setOf() in a concise manner.
    val mySet = setOf("alpha", "beta", "gamma")
    
  4. Adding and removing elements in a Kotlin set:

    • Since setOf() creates an immutable set, elements cannot be added or removed. Consider using mutableSetOf() for such operations.
    val mutableSet = mutableSetOf("dog", "cat", "bird")
    mutableSet.add("fish")
    mutableSet.remove("cat")
    
  5. Accessing elements in a set created with setOf():

    • Access elements by their values in the set.
    val fruitSet = setOf("apple", "banana", "orange")
    val firstFruit = fruitSet.first()
    
  6. Iterating over a set in Kotlin:

    • Use iteration to traverse through the elements of a set.
    val numberSet = setOf(1, 2, 3, 4, 5)
    for (number in numberSet) {
        // Process each number
    }
    
  7. Filtering and mapping with setOf() in Kotlin:

    • Leverage set functions for filtering and mapping.
    val evenNumbers = numberSet.filter { it % 2 == 0 }
    val squaredNumbers = numberSet.map { it * it }
    
  8. Set functions and methods in Kotlin:

    • Explore various set functions and methods for common operations.
    val setA = setOf(1, 2, 3)
    val setB = setOf(3, 4, 5)
    val unionSet = setA.union(setB)
    
  9. Null safety and setOf() in Kotlin:

    • Sets created with setOf() are non-nullable and don't allow null elements.
    val nonNullableSet = setOf("one", "two", "three")
    
  10. setOf() vs mutableSetOf() in Kotlin:

    • Choose between setOf() and mutableSetOf() based on whether you need immutability or mutability.
    val immutableSet = setOf("a", "b", "c")
    val mutableSet = mutableSetOf("x", "y", "z")
    
  11. Using setOf() with different data types in Kotlin:

    • Create sets with various data types using setOf().
    val stringSet = setOf("apple", "banana", "orange")
    val intSet = setOf(1, 2, 3, 4, 5)
    
  12. Copying and transforming sets in Kotlin:

    • Copy sets and apply transformations as needed.
    val originalSet = setOf("red", "green", "blue")
    val copiedSet = originalSet.toSet()
    val uppercasedSet = originalSet.map { it.toUpperCase() }