0
0
KotlinHow-ToBeginner · 3 min read

How to Find Distinct Elements in List Kotlin - Simple Guide

In Kotlin, you can find distinct elements in a list by using the distinct() function. This function returns a new list containing only unique elements, removing any duplicates.
📐

Syntax

The distinct() function is called on a list to return a new list with unique elements only.

  • list.distinct(): Returns a list with duplicates removed.
kotlin
val list = listOf(1, 2, 2, 3, 4, 4, 5)
val distinctList = list.distinct()
💻

Example

This example shows how to use distinct() to get unique elements from a list of numbers.

kotlin
fun main() {
    val numbers = listOf(1, 2, 2, 3, 4, 4, 5)
    val uniqueNumbers = numbers.distinct()
    println(uniqueNumbers)
}
Output
[1, 2, 3, 4, 5]
⚠️

Common Pitfalls

One common mistake is expecting distinct() to modify the original list. It does not; it returns a new list with unique elements.

Also, distinct() uses the default equality check, so for custom objects, you must override equals() and hashCode() for it to work correctly.

kotlin
fun main() {
    val list = mutableListOf(1, 2, 2, 3)
    list.distinct() // This does NOT change 'list'
    println(list) // Prints original list with duplicates

    val distinctList = list.distinct() // Correct way to get unique elements
    println(distinctList)
}
Output
[1, 2, 2, 3] [1, 2, 3]
📊

Quick Reference

Use distinct() to get unique elements from a list. It returns a new list and does not change the original.

For custom objects, ensure proper equality methods are defined.

FunctionDescription
distinct()Returns a new list with unique elements, removing duplicates.
distinctBy { selector }Returns unique elements based on a selector function.
toSet()Converts list to a set, which contains unique elements but is unordered.

Key Takeaways

Use the distinct() function to get unique elements from a Kotlin list.
distinct() returns a new list and does not modify the original list.
For custom objects, override equals() and hashCode() to ensure distinct() works correctly.
distinctBy() can be used to find unique elements based on a specific property.
toSet() is an alternative to get unique elements but returns an unordered collection.