To remove duplicates in an array in Kotlin, you can use the distinct
or toSet
methods.
In this example,
arrayWithDuplicates
with duplicate elements.distinct
method on arrayWithDuplicates
to remove duplicates.distinct
method returns a list with only unique elements.toTypedArray
method and print it to standard output.fun main(args: Array<String>) {
val arrayWithDuplicates = arrayOf(1, 2, 3, 4, 1, 2, 5, 6, 7, 3)
val arrayWithoutDuplicates = arrayWithDuplicates.distinct().toTypedArray()
println("Array without duplicates: ${arrayWithoutDuplicates.joinToString()}")
}
Array without duplicates: 1, 2, 3, 4, 5, 6, 7
In this example,
arrayWithDuplicates
with duplicate elements.toSet
method on arrayWithDuplicates
to convert it to a set, which automatically removes duplicates.toSet
method returns a set with only unique elements.toTypedArray
method and print it to standard output.fun main(args: Array<String>) {
val arrayWithDuplicates = arrayOf(1, 2, 3, 4, 1, 2, 5, 6, 7, 3)
val arrayWithoutDuplicates = arrayWithDuplicates.toSet().toTypedArray()
println("Array without duplicates: ${arrayWithoutDuplicates.joinToString()}")
}
Array without duplicates: 1, 2, 3, 4, 5, 6, 7
In this tutorial, we learned How to Remove Duplicates in an Array in Kotlin language with well detailed examples.