Kotlin - toSet() versus distinct()

Viewed 111

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.

1 Answers
Related