Kotlin Array.toMutableSet()

Kotlin Array.toMutableSet() Function

The Array.toMutableSet() function in Kotlin is used to convert an array to a mutable set. It creates a new mutable set containing the distinct elements of the original array.

Array.toMutableSet() function is useful when you want to eliminate duplicate elements and work with a collection of unique values that can be modified in your Kotlin code.

This tutorial will explore the syntax of the Array.toMutableSet() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.toMutableSet() function is as follows:

fun <T> Array<out T>.toMutableSet(): MutableSet<T>

Example for Array.toMutableSet() function

In this example, we’ll use toMutableSet() to convert an array of integers to a mutable set.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 2, 3, 2, 4, 5, 4, 6, 7, 8, 9)

    // Using toMutableSet() to convert the array of integers to a mutable set
    val mutableNumbersSet = numbersArray.toMutableSet()

    // Printing the original array and the resulting mutable set
    println("Input Array:\n${numbersArray.contentToString()}\n")
    println("Output Mutable Set:\n$mutableNumbersSet")
}

Output

Input Array:
[1, 2, 3, 2, 4, 5, 4, 6, 7, 8, 9]

Output Mutable Set:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Summary

In this tutorial, we’ve covered the Array.toMutableSet() function in Kotlin, its syntax, and how to use it to convert an array to a mutable set.