Kotlin List – Filter

To filter elements in a Kotlin List based on a predicate (condition), call filter() function on this List and pass the predicate to the filter() function as parameter.

In this tutorial, we will learn how to use filter() function on a List, to filter its elements based on a condition/predicate.

The syntax to call filter() function on a List with a predicate is

List.filter(predicate)

predicate is a lambda function that takes an element of the List as parameter and returns a boolean value.

Return Value

List.filter() function returns a List.

Elements of the List that return true for the given predicate, make it to the filtered List.

The original list on which filter() function is called, remains unchanged. Therefore, we can fall filter() function on a List, or a Mutable List.

Examples

In the following program, we will take a List of Integers and filter only even numbers.

Main.kt

fun main(args: Array<String>) {
    var myList = listOf(1, 4, 8, 5, 6, 9, 12, 10, 33)
    var filteredList = myList.filter { x -> x % 2 == 0 }
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Here, the lambda function: { x -> x % 2 == 0 } is the predicate to the filter() function.

For each element x in the List, only those elements that satisfy the condition x % 2 == 0 are returned in the resulting List.

Output

Original List : [1, 4, 8, 5, 6, 9, 12, 10, 33]
Filtered List : [4, 8, 6, 12, 10]

In the following example, we will take a list of Strings, and filter only those strings whose length is greater than 2.

Main.kt

fun main(args: Array<String>) {
    var myList = listOf("This", "is", "a", "test")
    var filteredList = myList.filter { x -> x.length > 2 }
    println("Original List : ${myList}")
    println("Filtered List : ${filteredList}")
}

Output

Original List : [This, is, a, test]
Filtered List : [This, test]

Conclusion

In this Kotlin Tutorial, we learned how to filter a List using a condition/predicate, using filter() function, with the help of examples.