Kotlin List toSet()
Syntax & Examples


Syntax of List.toSet()

The syntax of List.toSet() extension function is:

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

This toSet() extension function of List returns a Set of all elements.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We convert list1 to a Set using the toSet() function.
  • The resulting Set contains all unique elements from the list.
  • Finally, we print set1 to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;);
    val set1 = list1.toSet();
    println(set1);
}

Output

[a, p, l, e]

2 Example

In this example,

  • We create a list named list2 containing integers 10, 20, 30, 20, 30.
  • We convert list2 to a Set using the toSet() function.
  • The resulting Set contains unique elements from the list, removing duplicates.
  • Finally, we print set2 to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf(10, 20, 30, 20, 30);
    val set2 = list2.toSet();
    println(set2);
}

Output

[10, 20, 30]

3 Example

In this example,

  • We create a list named list3 containing strings 'apple', 'banana', 'orange', 'apple', 'banana'.
  • We convert list3 to a Set using the toSet() function.
  • The resulting Set contains unique elements from the list, removing duplicates.
  • Finally, we print set3 to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;apple&quot;, &quot;banana&quot;);
    val set3 = list3.toSet();
    println(set3);
}

Output

[apple, banana, orange]

Summary

In this Kotlin tutorial, we learned about toSet() extension function of List: the syntax and few working examples with output and detailed explanation for each example.