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
listcontaining the integers1, 2, 3, 4, 5. - We apply the
filterextension function onlistto filter out only the even numbers using the predicate{ it % 2 == 0 }. - The filtered elements are stored in the
resultlist. - 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 = list.filter { it % 2 == 0 };
println(result);
}Output
[2, 4]
2 Example
In this example,
- We create a list named
listcontaining the characters'a', 'b', 'c', 'd', 'e'. - We apply the
filterextension function onlistto filter out only the characters 'a' and 'e' using the predicate{ it in listOf('a', 'e') }. - The filtered elements are stored in the
resultlist. - 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 = list.filter { it in listOf('a', 'e') };
println(result);
}Output
[a, e]
3 Example
In this example,
- We create a list named
listcontaining the strings"apple", "banana", "orange", "grape". - We apply the
filterextension function onlistto filter out only the strings with length greater than 5 using the predicate{ it.length > 5 }. - The filtered elements are stored in the
resultlist. - Finally, we print the
resultlist 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.