Kotlin Set filterTo()
Syntax & Examples
Set.filterTo() extension function
The filterTo() extension function in Kotlin filters elements in a set, appending all elements that match the given predicate to the specified destination collection.
Syntax of Set.filterTo()
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.
Parameters
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. |
Return Type
Set.filterTo() returns value of type C
.
✐ Examples
1 Appending even numbers to a list
Using filterTo() to filter elements in a set, appending even numbers to a list.
For example,
- Create a set of integers.
- Create an empty list to hold the even elements.
- Define a predicate function that returns true for even numbers.
- Use filterTo() to append even numbers from the set to the list.
- Print the resulting list.
Kotlin Program
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)
}
Output
[2, 4, 6, 8, 10]
2 Appending non-null values to a set
Using filterTo() to filter elements in a set, appending non-null values to another set.
For example,
- Create a set containing integers and null values.
- Create an empty set to hold the non-null elements.
- Define a predicate function that returns true for non-null values.
- Use filterTo() to append non-null values from the set to the new set.
- Print the resulting set.
Kotlin Program
fun main() {
val mixedSet: Set<Int?> = setOf(1, 2, null, 4, null, 6)
val nonNullSet = mutableSetOf<Int?>()
mixedSet.filterTo(nonNullSet) { it != null }
println(nonNullSet)
}
Output
[1, 2, 4, 6]
3 Appending strings with length greater than 2 to a list
Using filterTo() to filter elements in a set, appending strings with length greater than 2 to a list.
For example,
- Create a set of strings.
- Create an empty list to hold the strings with length greater than 2.
- Define a predicate function that returns true for strings with length greater than 2.
- Use filterTo() to append strings with length greater than 2 from the set to the list.
- Print the resulting list.
Kotlin Program
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val longStrings = mutableListOf<String>()
strings.filterTo(longStrings) { it.length > 2 }
println(longStrings)
}
Output
["abc", "abcd"]
Summary
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.