Kotlin – Get distinct elements in Array

Get distinct elements in Array in Kotlin

To get distinct elements in given an Array in Kotlin, you can use Array.distinct() function.

["apple", "banana", "cherry", "banana", "apple"]

Distint elements
["apple", "banana", "cherry"]

Call the function distinct() on the Array object, and the function returns a List of distinct elements.

arr.distinct()

You may convert the returned List to an Array using List.toTypedArray() function.

arr.distinct().toTypedArray()

Examples

Get distinct element in given Array

In the following program, we take an Array of strings in arr, get all the distinct elements in the Array, and print them to output.

Kotlin Program

un main(args: Array<String>) {
    val arr = arrayOf<String>("apple", "banana", "cherry", "banana", "apple")
    val distinctArr = arr.distinct().toTypedArray()
    println(distinctArr.contentToString())
}

Output

[apple, banana, cherry]