Kotlin List filterTo()
Syntax & Examples
Syntax of List.filterTo()
The syntax of List.filterTo() extension function is:
fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo( destination: C, predicate: (T) -> Boolean ): CThis filterTo() extension function of List appends all elements matching the given predicate to the given destination.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining integers. - We create an empty mutable list named
resultto store the filtered elements. - We apply the
filterToextension function onlistto filter out even numbers and append them toresult. - Finally, we print the
resultlist to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val result = mutableListOf<Int>();
list.filterTo(result) { it % 2 == 0 };
println(result);
}Output
[2, 4]
2 Example
In this example,
- We create a list named
listcontaining characters. - We create an empty mutable list named
resultto store the filtered elements. - We apply the
filterToextension function onlistto filter out characters 'a' and 'e' and append them toresult. - Finally, we print the
resultlist to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
val result = mutableListOf<Char>();
list.filterTo(result) { it in listOf('a', 'e') };
println(result);
}Output
[a, e]
3 Example
In this example,
- We create a list named
listcontaining strings. - We create an empty mutable list named
resultto store the filtered elements. - We apply the
filterToextension function onlistto filter out strings with a length greater than 5 and append them toresult. - Finally, we print the
resultlist to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "orange", "kiwi", "mango");
val result = mutableListOf<String>();
list.filterTo(result) { it.length > 5 };
println(result);
}Output
[banana, orange]
Summary
In this Kotlin tutorial, we learned about filterTo() extension function of List: the syntax and few working examples with output and detailed explanation for each example.