Kotlin Array distinct()

Kotlin Array distinct()

In Kotlin, the Array distinct() function is used to obtain a new array containing only the distinct elements of the original array. It removes duplicate elements, leaving only unique elements in the returned array.

This function is helpful when you want to eliminate duplicate values from an array.

In this tutorial, we’ll explore the syntax of the distinct() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the distinct() function is:

fun <T> Array<out T>.distinct(): List<T>

The distinct() function returns a new list containing only the distinct elements of the array.

Examples for Array distinct() function

1. Using distinct() to Remove Duplicate Numbers

In this example, we’ll use distinct() to create a new array with duplicate numbers removed.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(1, 2, 3, 4, 2, 5, 3, 6, 7, 8, 1)

    // Using distinct() to remove duplicate numbers
    val distinctNumbers = numbersArray.distinct()

    // Printing the original array and the result
    println("Numbers: \n${numbersArray.joinToString(", ")}")
    println("Distinct Numbers: \n${distinctNumbers.joinToString(", ")}")
}

Output

Numbers: 
1, 2, 3, 4, 2, 5, 3, 6, 7, 8, 1
Distinct Numbers: 
1, 2, 3, 4, 5, 6, 7, 8

2. Using distinct() to Remove Duplicate Words

In this example, we’ll use distinct() to create a new array with duplicate words removed.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "orange", "apple", "kiwi", "banana")

    // Using distinct() to remove duplicate words
    val distinctWords = wordsArray.distinct()

    // Printing the original array and the result
    println("Words: \n${wordsArray.joinToString(", ")}")
    println("Distinct Words: \n${distinctWords.joinToString(", ")}")
}

Output

Words: 
apple, banana, orange, apple, kiwi, banana
Distinct Words: 
apple, banana, orange, kiwi

Summary

In this tutorial, we’ve covered the distinct() function in Kotlin arrays, its syntax, and how to use it to obtain a new array with duplicate elements removed.