Kotlin Array.toSortedSet()

Kotlin Array.toSortedSet() Tutorial

The Array.toSortedSet() function in Kotlin is used to convert an array to a sorted set. It creates a new sorted set containing the distinct elements of the original array in natural order or according to a specified comparator.

Whether using natural order or a custom comparator, this Array.toSortedSet() function is valuable when you need the elements of your set to be in a specific order.

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

Syntax

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

fun <T> Array<out T>.toSortedSet(): SortedSet<T>

or with a custom comparator:

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

where

ParameterDescription
comparatorFunction that take the element in array as argument and returns a value, where the returned value is used for comparison between the elements.
Parameters for Array.toSortedArray()

Examples for Array.toSortedSet() function

1. Using toSortedSet() to convert Array to a SortedSet

In this example, we’ll take an array of integers in numbersArray, and use toSortedSet() to convert this array of integers to a sorted set where the elements are sorted in natural order.

Kotlin Program

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

    // Using toSortedSet() to convert the array of integers to a sorted set
    val sortedNumbersSet = numbersArray.toSortedSet()

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

Output

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

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

The duplicate elements in the input array are ignored for the resulting set.

2. Using toSortedSet() with a Custom Comparator

In this example, we’ll use toSortedSet() with a custom comparator to convert an array of strings to a sorted set based on their lengths.

For example, even though the string "apple" is less than the string "kiwi" lexicographically, when comparing their lengths, "apple" is greater than "kiwi".

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "orange", "grape", "kiwi")

    // Using toSortedSet() with a custom comparator to convert the array of strings to a sorted set
    val sortedWordsSet = wordsArray.toSortedSet(compareBy { it.length })

    // Printing the original array and the resulting sorted set
    println("Words Array:\n${wordsArray.contentToString()}\n")
    println("Sorted Words Set:\n$sortedWordsSet")
}

Output

Words Array:
[apple, banana, orange, grape, kiwi]

Sorted Words Set:
[kiwi, apple, banana]

Summary

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