Reputation: 42270
In Kotlin, I could obtain the distinct elements of an Iterable<T>
using the following two methods...
Calling .toSet()
val items = listOf(1, 2, 2, 3)
val distinctItems: Set<Int> = items.toSet()
Calling .distinct()
val items = listOf(1, 2, 2, 3)
val distinctItems: List<Int> = items.distinct()
Aside from the fact that the return type is different (Set<Int>
versus List<Int>
) is there any advantage (i.e. performance) of calling one over the other?
Note: It seems that Kotlin favours the use of List<T>
over Set<T>
for most operations, and I guess that makes sense where lists of items are probably more common than sets of items. I tend to use Set<T>
more often than not, especially where set semantics make more sense than list semantics.
Upvotes: 6
Views: 1798
Reputation: 6793
Iterable.distinct()
uses a Set
internally. So basically you can expect O(#distinctElements) of performance impact.
public fun <T> Iterable<T>.distinct(): List<T> {
return this.toMutableSet().toList()
}
Upvotes: 4