Skip to main content

How to remove duplicates from an array in Kotlin

How to remove duplicates from an array in Kotlin.

Here is a detailed step-by-step tutorial on how to remove duplicates from an array in Kotlin.

Step 1: Create an Array

First, we need to create an array that contains some duplicates. Here's an example of how to create an array in Kotlin:

val array = arrayOf(1, 2, 3, 1, 2, 4, 5, 3)

In this example, the array contains duplicate elements: 1, 2, and 3.

Step 2: Convert the Array to a Set

To remove duplicates from the array, we can convert it to a set. A set is a collection that does not allow duplicate elements. Here's how to convert the array to a set:

val set = array.toSet()

In this example, the toSet() function is used to convert the array to a set.

Step 3: Convert the Set back to an Array

After converting the array to a set, we need to convert it back to an array. This step is necessary if you need the final result to be an array. Here's how to convert the set back to an array:

val newArray = set.toIntArray()

In this example, the toIntArray() function is used to convert the set back to an array.

Step 4: Print the Result

Finally, we can print the new array that contains no duplicates. Here's an example of how to print the resulting array:

println(newArray.contentToString())

In this example, the contentToString() function is used to convert the array to a string representation that can be printed.

Alternative Approach: Use a MutableSet

Instead of converting the array to a set and then back to an array, we can use a MutableSet to directly remove duplicates from the array. Here's an example:

val mutableSet = mutableSetOf<Int>()
array.forEach { mutableSet.add(it) }
val newArray = mutableSet.toIntArray()

In this example, we create a MutableSet and iterate over each element in the array. We add each element to the set, which automatically removes duplicates. Finally, we convert the set to an array.

That's it! You've successfully removed duplicates from an array in Kotlin. You can choose either the set approach or the mutable set approach based on your requirements.