Kotlin Array - toSet() Function



The Kotlin array toSet() function is used to convert an array or collection into a set. This function return a set preserves the element iteration order of the original array.

The sets does not contains duplicate elements, any duplicate in the array will removed in the resulting set.

Syntax

Following is the syntax of Kotlin array toSet() function −

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

Parameters

This function does not accepts any parameter.

Return value

This function returns a set containing all elements of an array in the same order.

Example 1

Following is a basic example to demonstrate the use of toSet() function to return a set −

fun main(args: Array<String>){
   var arr = arrayOf(3, 4, 5, 6)
   print("Array: ")
   println(arr.joinToString())

   // use toSet function to convert an array to set
   val arr_to_set = arr.toSet()
   println("set: "+ arr_to_set)
}

Output

The above code generate following output −

Array: 3, 4, 5, 6
set: [3, 4, 5, 6]

Example 2

Let's see another example. Here, we use the toSet function to return a set containing elements of an array in same order −

fun main(args: Array<String>) {
   // array of integers
   val intArray = arrayOf(1, 2, 3, 4, 5)
   
   // Convert the array to a set
   val intSet: Set<Int> = intArray.toSet()
   
   // display the list
   println("Set: $intSet")
}

Output

Following is the output −

Set: [1, 2, 3, 4, 5]

Example 3

Let's continue with the another example to convert an array to a set and demonstrate how duplicates are removed −

fun main(args: Array<String>) {
   // Define an array with some duplicate elements
   val array = arrayOf(1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 6)

   // Convert the array to a set
   val set = array.toSet()

   // Display the original array and the resulting set
   println("Original array: ${array.joinToString(", ")}")
   println("Set: ${set.joinToString(", ")}")
}

Output

The above code produce following output −

Original array: 1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 6
Set: 1, 2, 3, 4, 5, 6, 7, 8
kotlin_arrays.htm
Advertisements