This article explores different ways to remove duplicates from an array in Kotlin.

Since Arrays in Kotlin are non-dynamic and holds a fixed number of items of a single type, we cannot remove elements from it. The only option is to create a new array with the distinct values. There are many ways to do this:

1. Using distinct() function

A simple solution to filter the distinct elements present in the array is using the distinct() library function. After getting the distinct elements, accumulate all elements into a new array by invoking the corresponding to*Array() function. This would translate to the following code:

Download Code

 
The above solution preserves the relative order of elements in the array. We can also use the distinctBy() function that returns elements with distinct keys as returned by the specified selector function.

Download Code

2. Using a Set

Alternatively, we can build a Set from the array elements and then convert the Set back into the array. This will result in all distinct elements in the array, since a Set discards duplicates. However, it destroys the relative order of the array elements.

Download Code

3. Sorting

Finally, we can sort the array and compare every pair of adjacent elements to identify and remove the duplicates. This can be implemented as follows in Kotlin.

Download Code

That’s all about removing duplicates from an array in Kotlin.