Kotlin List - toSet() Function



The Kotlin List toSet() function is used to convert the list into a set. The returned set preserves the element order iteration of the original list.

Get additional information about the toSet() function for arrays, Visit Here

The set does not allow duplicate elements, so the list may or may not contain duplicates. Set returns only distinct elements from the list.

Syntax

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

fun <T> list<T>.toSet(): Set<T>

Parameters

This function does not accepts any parameters.

Return value

This function returns a set that contains the distinct element from the list.

Example 1

Let's see a basic example of the toSet() function, which return a set that contains unique elements from list −

fun main(args: Array<String>) {
   val numbers = listOf(1, 2, 2, 3, 4, 4, 5)
   val uniqueNumbers = numbers.toSet()
   println("Unique numbers: $uniqueNumbers")
}

Output

Following is the output −

Unique numbers: [1, 2, 3, 4, 5]

Example 2: Using toSet With Empty List

If the list is empty the toSet() function returns a empty set −

fun main(args: Array<String>) {
   val emptyList = listOf<Int>()
   val emptySet = emptyList.toSet()
   println("Empty set: $emptySet")
}

Output

Following is the output −

Empty set: []

Example 3: If a List Contains Any Type of Data

This is another example of the toSet() function. If a list contains multiple data types, the set will also contain multiple data type with distinct elements −

fun main(args: Array<String>) {
   val a_list = listOf<Any>(1, 2, 1, "tutorialspoint", "India", 'A', 'B', 'B')
   val a_set = a_list.toSet()
   println("A list: $a_list")
   println("A Set: $a_set")
}

Output

Following is the output −

A list: [1, 2, 1, tutorialspoint, India, A, B, B]
A Set: [1, 2, tutorialspoint, India, A, B]
kotlin_lists.htm
Advertisements