How to Remove Duplicates from List in Kotlin Easily
In Kotlin, you can remove duplicates from a list by converting it to a
Set using toSet() or by using the distinct() function which returns a list without duplicates. Both methods keep only unique elements, but distinct() preserves the original order.Syntax
To remove duplicates from a list in Kotlin, you can use either:
list.toSet(): Converts the list to a set, removing duplicates but not preserving order.list.distinct(): Returns a new list with duplicates removed, preserving the original order.
kotlin
val uniqueSet = list.toSet() val uniqueList = list.distinct()
Example
This example shows how to remove duplicates from a list using both toSet() and distinct(). It prints the results so you can see the difference.
kotlin
fun main() {
val numbers = listOf(1, 2, 2, 3, 4, 4, 5)
val uniqueSet = numbers.toSet()
println("Using toSet(): $uniqueSet")
val uniqueList = numbers.distinct()
println("Using distinct(): $uniqueList")
}Output
Using toSet(): [1, 2, 3, 4, 5]
Using distinct(): [1, 2, 3, 4, 5]
Common Pitfalls
One common mistake is expecting toSet() to preserve the order of elements. Sets do not guarantee order, so the result may be unordered. If order matters, use distinct() instead.
Another pitfall is modifying the original list expecting duplicates to be removed. Both methods return new collections and do not change the original list.
kotlin
fun main() {
val list = listOf(3, 1, 2, 3, 2)
// Wrong: expecting original list to change
list.toSet()
println("Original list after toSet(): $list")
// Right: assign the result
val unique = list.distinct()
println("Unique list with distinct(): $unique")
}Output
Original list after toSet(): [3, 1, 2, 3, 2]
Unique list with distinct(): [3, 1, 2]
Quick Reference
Here is a quick summary of methods to remove duplicates from a list in Kotlin:
| Method | Description | Preserves Order |
|---|---|---|
| toSet() | Converts list to a set, removes duplicates | No |
| distinct() | Returns a list with duplicates removed | Yes |
Key Takeaways
Use
distinct() to remove duplicates while keeping the original order.Use
toSet() to remove duplicates but order is not guaranteed.Both methods return new collections and do not modify the original list.
Assign the result to a variable to use the list without duplicates.
For simple duplicate removal,
distinct() is usually the best choice.