Kotlin List.distinct() Function

The Kotlin List.distinct() function is used to get distinct elements of this list. distinct() returns a new List formed with the distinct items from this given list. It does not modify the original list.

Syntax

The syntax of List.distinct() function is

</>
Copy
fun <T> List<T>.distinct(): List<T>

Returns a list containing only distinct elements from the given collection.

Examples

In this example, we take a list of numbers, and find the distinct elements using List.distinct() function.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf(2, 4, 1, 4, 6, 2, 3)
    var result = list.distinct()
    println(result)
}

Output

[2, 4, 1, 6, 3]

In this example, we take a list of strings, and find the distinct strings using List.distinct() function.

Kotlin Program

</>
Copy
fun main(args: Array<String>) {
    var list = listOf("apple", "mango", "apple")
    var result = list.distinct()
    println(result)
}

Output

[apple, mango]

Conclusion

In this Kotlin Tutorial, we learned how to find distinct elements of a list, using Kotlin List.distinct() function.