How to remove duplicates from an array Kotlin with example
This tutorial explains multiple ways to remove duplicate elements
The first way to use the distinct() function is to return an array of unique elements and elements in insertion order.
The second way using toSet(), returns a Set
of elements and order is not preserved.
The third way using toMutableSet(), returns the MutableSet
of elements and order is preserved.
The second way using toHashSet(), returns HashSet
of elements and order is not preserved
Array finds unique elements
There are multiple ways to remove duplicate elements from an array.
- using disticnt array function
distinct()
function removes an duplicate elements. Elements can be strings or any type and return unique elements.
The size of the original is always not the same as the result array if there are duplicate elements.
It returns an Array type and the result array order 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]
}
- toSet function
toSet function converts the array to Set and Set is a Data structure that does not allow to save duplicate elements by design.
Result array elements are not ordered, It always returns Set
, not Array
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 way to return unique elements. It converts the MutableSet type and stores unique elements. The return type is MutableSet.
Result Set stores elements in Ordered 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 converts the HashSet
type and stores unique elements. The return type is 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 are used to remove duplicate elements from an array.
use the distinct() function, If you want to return an element to an Array.
use toSet() function, if the result type expected is Set.