Kotlin List filter()
Syntax & Examples
Syntax of List.filter()
The syntax of List.filter() extension function is:
fun <T> Iterable<T>.filter( predicate: (T) -> Boolean ): List<T>
This filter() extension function of List returns a list containing only elements matching the given predicate.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers1, 2, 3, 4, 5
. - We apply the
filter
extension function onlist
to filter out only the even numbers using the predicate{ it % 2 == 0 }
. - The filtered elements are stored in the
result
list. - 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 = list.filter { it % 2 == 0 };
println(result);
}
Output
[2, 4]
2 Example
In this example,
- We create a list named
list
containing the characters'a', 'b', 'c', 'd', 'e'
. - We apply the
filter
extension function onlist
to filter out only the characters 'a' and 'e' using the predicate{ it in listOf('a', 'e') }
. - The filtered elements are stored in the
result
list. - 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 = list.filter { it in listOf('a', 'e') };
println(result);
}
Output
[a, e]
3 Example
In this example,
- We create a list named
list
containing the strings"apple", "banana", "orange", "grape"
. - We apply the
filter
extension function onlist
to filter out only the strings with length greater than 5 using the predicate{ it.length > 5 }
. - The filtered elements are stored in the
result
list. - Finally, we print the
result
list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "orange", "grape");
val result = list.filter { it.length > 5 };
println(result);
}
Output
[banana, orange]
Summary
In this Kotlin tutorial, we learned about filter() extension function of List: the syntax and few working examples with output and detailed explanation for each example.