Kotlin Array.toSet()

Kotlin Array.toSet() Tutorial

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

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

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

Syntax

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

fun <T> Array<out T>.toSet(): Set<T>

Examples for Array.toSet() function

1. Convert given Array of integer to a Set

In this example, we’ll take an array of integers in numbersArray, and use toSet() to convert this array of integers to a set.

Kotlin Program

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

    // Using toSet() to convert the array of integers to a set
    val uniqueNumbersSet = numbersArray.toSet()

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

Output

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

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

Since, Set can contain only unique element, only one occurrence of the elements 2 and 4 are considered in the returned Set.

Summary

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