Provide distinctBy(keySelector) method for collections and sequences.

Implement distinct() and toMutableSet() for sequences.
Breaking change: distinct() now returns List instead of Set.

#KT-5834 Fixed
#KT-6063 Fixed
This commit is contained in:
Ilya Gorbunov
2015-04-27 16:36:53 +03:00
parent 46d91b2606
commit 6a3cb0eff8
5 changed files with 344 additions and 39 deletions
@@ -6,7 +6,7 @@ fun sets(): List<GenericFunction> {
val templates = arrayListOf<GenericFunction>()
templates add f("toMutableSet()") {
exclude(Strings, Sequences)
exclude(Strings)
doc { "Returns a mutable set containing all distinct elements from the given collection." }
returns("MutableSet<T>")
body {
@@ -24,18 +24,66 @@ fun sets(): List<GenericFunction> {
return set
"""
}
doc(Sequences) { "Returns a mutable set containing all distinct elements from the given sequence." }
body(Sequences) {
"""
val set = LinkedHashSet<T>()
for (item in this) set.add(item)
return set
"""
}
}
templates add f("distinct()") {
exclude(Strings, Sequences)
doc { "Returns a set containing all distinct elements from the given collection." }
exclude(Strings)
val collectionDoc = """
Returns a list containing only distinct elements from the given collection.
returns("Set<T>")
The elements in the resulting list are in the same order as they were in the source collection.
"""
doc { collectionDoc }
returns("List<T>")
body { "return this.toMutableSet().toList()" }
doc(Sequences) { collectionDoc.replace("list", "sequence").replace("collection", "sequence") }
returns(Sequences) { "Sequence<T>" }
body(Sequences) { "return this.distinctBy { it }" }
}
templates add f("distinctBy(keySelector: (T) -> K)") {
exclude(Strings)
val collectionDoc = """
Returns a list containing only distinct elements from the given collection according to the [keySelector].
The elements in the resulting list are in the same order as they were in the source collection.
"""
doc { collectionDoc }
inline(true)
typeParam("K")
returns("List<T>")
body {
"""
return this.toMutableSet()
val set = HashSet<K>()
val list = ArrayList<T>()
for (e in this) {
val key = keySelector(e)
if (set.add(key))
list.add(e)
}
return list
"""
}
inline(false, Sequences)
doc(Sequences) { collectionDoc.replace("list", "sequence").replace("collection", "sequence") }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return DistinctSequence(this, keySelector)
"""
}
}
templates add f("union(other: Iterable<T>)") {