Kotlin List.distinctBy() – Examples

Kotlin List.distinctBy()

The List.distinctBy() function in Kotlin is used to return a list containing only the elements from the original list having distinct keys produced by the given selector function.

Syntax

fun <T, K> Iterable<T>.distinctBy(selector: (T) -> K): List<T>

The function takes a selector function that is applied to each element, and the distinct elements are determined based on the keys produced by this function.

ParameterDescription
TThe type of elements in the list.
KThe type of keys produced by the selector function.
selectorThe function that produces keys used to determine distinct elements.

T is the type of elements in the list.

Example 1: Basic Usage of List.distinctBy()

Filter a list of names based on the first character to get distinct initials.

Kotlin Program

fun main() {
    val names = listOf("Alice", "Bob", "Charlie", "David", "Eva", "Eleanor")
    val distinctInitials = names.distinctBy { it.first() }

    println(distinctInitials)
}

Output


[Alice, Bob, Charlie]

This example uses the distinctBy function to filter the list of names based on the first character, resulting in a list of distinct initials.

Example 2: Using List.distinctBy() with Custom Objects

Filter a list of custom objects based on a property to get distinct values.

Kotlin Program

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

fun main() {
    val people = listOf(
        Person(1, "Alice"),
        Person(2, "Bob"),
        Person(3, "Alice"),
        Person(4, "Charlie")
    )

    val distinctNames = people.distinctBy { it.name }

    println(distinctNames)
}

Output


[Person(id=1, name=Alice), Person(id=2, name=Bob), Person(id=4, name=Charlie)]

This example uses the distinctBy function to filter a list of custom objects based on the name property, resulting in a list of distinct names.

Summary

The List.distinctBy() function in Kotlin is a convenient way to obtain a list of distinct elements based on a key extracted by a selector function. It is useful when you want to filter a list and retain only the elements with distinct properties.