Kotlin Array.distinctBy()

Kotlin Array.distinctBy() function

In Kotlin, the distinctBy() function is used to return a list of distinct elements from the original array based on the results of applying an transformation function to each element. The transformation function allows you to specify a custom criterion for determining the distinctness of elements.

This function is particularly useful when you want to obtain unique elements from an array based on some property or transformation.

In this tutorial, we’ll explore the syntax of the distinctBy() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the distinctBy() function is as follows:

inline fun <T, K> Array<out T>.distinctBy(
    selector: (T) -> K
): List<T>

where

ParameterDescription
selectorA lambda function that takes an element from the array and returns the property or transformation based on which distinctness is determined.
Parameter of Array distinctBy() function

The function returns a List.

Examples for Array distinctBy() function

1. Distinct Elements Based on Length

In this example, we’ll use distinctBy() to obtain distinct elements from an array based on their lengths.

We shall take an array of string values, and find the distinct objects in this array based on the string length.

Kotlin Program

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

    // Obtaining distinct elements based on length
    val distinctByLength = wordsArray.distinctBy { it.length }

    // Printing the original array and the result
    println("Given Array\n${wordsArray.contentToString()}\n")
    println("Distinct Elements by Length\n[${distinctByLength.joinToString(", ")}]")
}

Output

Given Array
[apple, banana, orange, grape, kiwi, apple]

Distinct Elements by Length
[apple, banana, kiwi]

Explanation

Given Array → [apple, banana, orange, grape, kiwi, apple]
Lengths     →  5      6       6       5      4     5
Distinct    →  5      6                      4
Result      → [apple, banana,                kiwi       ]

2. Distinct Elements Based on Property

In this example, we’ll use distinctBy() to obtain distinct elements from an array based on a custom property of each element.

We shall take an array of custom type Person objects, and find the distinct objects in this array based on the name property of these Person objects.

Kotlin Program

data class Person(val id: Int, val name: String)

fun main() {
    val peopleArray = arrayOf(
        Person(1, "Alice"),
        Person(2, "Bob"),
        Person(3, "Alice"),
        Person(4, "Charlie"),
        Person(5, "Bob")
    )

    // Obtaining distinct elements based on the 'name' property
    val distinctByName = peopleArray.distinctBy { it.name }

    // Printing the original array and the result
    println("People Array: \n${peopleArray.joinToString("\n")}\n")
    println("Distinct People by Name: \n${distinctByName.joinToString("\n")}")
}

Output

People Array: 
Person(id=1, name=Alice)
Person(id=2, name=Bob)
Person(id=3, name=Alice)
Person(id=4, name=Charlie)
Person(id=5, name=Bob)

Distinct People by Name: 
Person(id=1, name=Alice)
Person(id=2, name=Bob)
Person(id=4, name=Charlie)

3. Distinct Elements Based on the Intrinsic Value

In this example, we’ll use distinctBy() to obtain distinct elements from an array based on their intrinsic values.

We shall take an array of strings, wordsArray and get the distinct elements in this array based on the element value itself.

Kotlin Program

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

    // Obtaining distinct elements based on length
    val distinctElements = wordsArray.distinctBy { it }

    // Printing the original array and the result
    println("Given Array\n${wordsArray.contentToString()}\n")
    println("Distinct Elements by Value\n[${distinctElements.joinToString(", ")}]")
}

Output

Given Array
[apple, banana, banana, grape, kiwi, apple]

Distinct Elements by Value
[apple, banana, grape, kiwi]

Summary

In this tutorial, we’ve covered the distinctBy() function in Kotlin Array, its syntax, and how to use it to obtain distinct elements based on a specified property or transformation.