Kotlin List toSortedSet()
Syntax & Examples


Syntax of List.toSortedSet()

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

fun <T> Iterable<T>.toSortedSet( comparator: Comparator<in T> ): SortedSet<T>

This toSortedSet() extension function of List returns a new SortedSet 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 SortedSet using the toSortedSet() function.
  • The resulting SortedSet contains all unique elements from the list, sorted in natural order.
  • Finally, we print sortedSet1 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 sortedSet1 = list1.toSortedSet();
    println(sortedSet1);
}

Output

[a, e, l, p]

2 Example

In this example,

  • We create a list named list2 containing integers 30, 10, 20, 40, 20.
  • We convert list2 to a SortedSet using the toSortedSet() function.
  • The resulting SortedSet contains unique elements from the list, sorted in natural order.
  • Finally, we print sortedSet2 to standard output.

Kotlin Program

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

Output

[10, 20, 30, 40]

3 Example

In this example,

  • We create a list named list3 containing strings 'apple', 'banana', 'orange', 'banana', 'apple'.
  • We convert list3 to a SortedSet using the toSortedSet() function.
  • The resulting SortedSet contains unique elements from the list, sorted in natural order.
  • Finally, we print sortedSet3 to standard output.

Kotlin Program

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

Output

[apple, banana, orange]

Summary

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