Remove duplicates from an array in Kotlin
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeDuplicates(array: IntArray): IntArray { return array.distinct().toIntArray() } fun main() { val array: IntArray = intArrayOf(2, 4, 1, 2, 1, 2, 4, 5) val distinct = removeDuplicates(array) println(distinct.contentToString()) // [2, 4, 1, 5] } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeDuplicates(array: IntArray): IntArray { return array.distinctBy { it }.toIntArray() } fun main() { val array: IntArray = intArrayOf(2, 4, 1, 2, 1, 2, 4, 5) val distinct = removeDuplicates(array) println(distinct.contentToString()) // [2, 4, 1, 5] } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeDuplicates(array: IntArray): IntArray { return array.toSet().toIntArray() } fun main() { val array: IntArray = intArrayOf(2, 4, 1, 2, 1, 2, 4, 5) val distinct = removeDuplicates(array) println(distinct.contentToString()) // [1, 2, 4, 5] } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun removeDuplicates(array: IntArray): IntArray { array.sort() var k = 0 for (i in array.indices) { if (i == 0 || array[i] != array[i - 1]) { array[k++] = array[i] } } return array.copyOf(k) } fun main() { val array: IntArray = intArrayOf(2, 4, 1, 2, 1, 2, 4, 5) val distinct = removeDuplicates(array) println(distinct.contentToString()) // [1, 2, 4, 5] } |
That’s all about removing duplicates from an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)