Kotlin List.distinctBy() Function

The Kotlin List.distinctBy() function is used to get a list of elements whose keys returned by given selector function are distinct.

Syntax

The syntax of List.distinctBy() function is

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

Returns

List.

Examples

In this example, we select elements from the list of strings whose distinction is based on starting character.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf("apple", "banana", "mango", "berry")
    var result = list.distinctBy { it[0] }
    println(result)
}

Output

[apple, banana, mango]

Since, elements banana and berry have same first character, these are considered to be same by distinctBy() function.

Conclusion

In this Kotlin Tutorial, we learned how to find elements of a list for which the values returned by a function are distinct, using Kotlin List.distinctBy() function.