What is "distinct()" method in Kotlin?

Kotlin is a versatile and modern programming language, known for its concise syntax and powerful features. It offers a wide range of functionalities for Android app development and backend applications.

The distinct() method

The distinct() method removes duplicate elements from collections, ensuring that each element appears only once. Eliminating duplicates provides accurate results in various computations like counting, calculations, and comparisons and improves overall performance.

Syntax

Here is the basic syntax for the distinct() method:

val distinctCollection = collection.distinct()
Syntax for distinct() method
  • collection represents the collection you want to remove duplicates from.

Note: Make sure you have Kotlin installed. To learn more about the Kotlin installation on your system, click here.

Code

Let’s demonstrate the usage of the distinct() method with the simple code given below.

Suppose you have a list of numbers, and we want to remove any duplicate numbers and display only the distinct elements in the list.

fun main() {
val numbers = listOf(1, 2, 3, 2, 4, 5, 3, 6, 7, 4, 8, 9, 10, 5)
val distinctNumbers = numbers.distinct()
println("Original Numbers: $numbers")
println("Distinct Numbers: $distinctNumbers")
}

Code explanation

  • Line 1–2: Firstly, we define a list of numbers that includes duplicates.

  • Line 4: Next, we apply the distinct() method to the numbers list, resulting in a new list containing only the distinct elements.

  • Line 6–8: Finally, we print both the original and distinct numbers on the console.

Output

Upon execution, the code will remove the duplicate elements from the original list of numbers and display the distinct numbers.

The output looks something like this:

Original Numbers: [1, 2, 3, 2, 4, 5, 3, 6, 7, 4, 8, 9, 10, 5]
Distinct Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Conclusion

Therefore, the distinct() method in Kotlin comes in handy for removing duplicate elements from collections. Developers can enhance readability, and optimize performance by employing this method in their applications. It can help streamline the code when working with various types of collections and provides data integrity.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved