How to remove duplicates from an array Kotlin with example

This tutorial explores various methods for removing duplicate elements from a collection.

The first method utilizes the distinct()function, which returns an array of unique elements while preserving the order of insertion.

The second approach involves using toSet(), which returns a Set of elements. However, the order is not maintained.

The third method employs toMutableSet(), resulting in a MutableSet of elements with the order preserved.

Another alternative is to use toHashSet(), which returns a HashSet of elements. However, similar to toSet(), the order is not preserved.

Using array distinct() Function

The first method involves utilizing the distinct() function, which returns an array of unique elements while preserving the order of insertion

The size of the original array may not always be the same as the result array if there are duplicate elements.

The function returns an array, and the order of elements in the result array is preserved.

here is an example

import java.util.Arrays

fun main() {
    val numbers: Array<Int> = arrayOf(11, 11,12, 13, 14, 15,11)
    println(Arrays.toString(numbers)) // [11, 11, 12, 13, 14, 15, 11]

    println(numbers.distinct())// [11, 12, 13, 14, 15]

}

Use toSet function

The toSet function converts the array to a Set. A Set is a data structure that, by design, does not allow the storage of duplicate elements.

The elements in the resulting array are not ordered. This function always returns a Set, not an Array.

Additionally, You have to convert the Set to an Array before you can use it.

import java.util.Arrays

fun main() {
    val numbers: Array<Int> = arrayOf(11, 11,12, 13, 14, 15,11)
    println(Arrays.toString(numbers))
    println(numbers.toSet())

}

Using the toMutableSet function

Another method to obtain unique elements is by using the toMutableSet function. This function converts the array to a MutableSet and stores unique elements. The return type is a MutableSet.

The resulting set maintains the order of elements due to the implementation of LinkedHashSet.

import java.util.Arrays

fun main() {
    val strs: Array<String> = arrayOf("one","two","one","three")
    println(Arrays.toString(strs)) // [one, two, one, three]
    println(strs.toMutableSet()) //[one, two, three]

}

using the toHashSet function

It transforms the array into a HashSet type, preserving unique elements. The resulting type is a HashSet.

import java.util.Arrays

fun main() {
    val strs: Array<String> = arrayOf("one","two","one","three")
    println(Arrays.toString(strs))
    println(strs.toHashSet())

}

Conclusion

Multiple approaches exist for removing duplicate elements from an array. Choose the method based on the desired result type: use distinct() for an array, toSet() for a Set, or toMutableSet() for a MutableSet.