The filterTo() extension function in Kotlin filters elements in a set, appending all elements that match the given predicate to the specified destination collection.
The syntax of Set.filterTo() extension function is:
fun <T, C : MutableCollection<in T>> Set<T>.filterTo(destination: C, predicate: (T) -> Boolean): C
This filterTo() extension function of Set appends all elements matching the given predicate to the given destination.
Parameter | Optional/Required | Description |
---|---|---|
destination | required | The collection to which the matching elements will be appended. |
predicate | required | A function that takes an element and returns true if the element should be included in the result. |
Set.filterTo() returns value of type C
.
Using filterTo() to filter elements in a set, appending even numbers to a list.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenList = mutableListOf<Int>()
numbers.filterTo(evenList) { it % 2 == 0 }
println(evenList)
}
[2, 4, 6, 8, 10]
Using filterTo() to filter elements in a set, appending non-null values to another set.
For example,
fun main() {
val mixedSet: Set<Int?> = setOf(1, 2, null, 4, null, 6)
val nonNullSet = mutableSetOf<Int?>()
mixedSet.filterTo(nonNullSet) { it != null }
println(nonNullSet)
}
[1, 2, 4, 6]
Using filterTo() to filter elements in a set, appending strings with length greater than 2 to a list.
For example,
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val longStrings = mutableListOf<String>()
strings.filterTo(longStrings) { it.length > 2 }
println(longStrings)
}
["abc", "abcd"]
In this Kotlin tutorial, we learned about filterTo() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.