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 ): C

This 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 list containing integers.
  • We create an empty mutable list named result to store the filtered elements.
  • We apply the filterTo extension function on list to filter out even numbers and append them to result.
  • Finally, we print the result list 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 list containing characters.
  • We create an empty mutable list named result to store the filtered elements.
  • We apply the filterTo extension function on list to filter out characters 'a' and 'e' and append them to result.
  • Finally, we print the result list 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 list containing strings.
  • We create an empty mutable list named result to store the filtered elements.
  • We apply the filterTo extension function on list to filter out strings with a length greater than 5 and append them to result.
  • Finally, we print the result list 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.