Kotlin List - filter() Function



The Kotlin List filter() function filters the element of a list based on a given predicate. It returns a new list containing only those elements that satisfy the condition defined by the predicate.

Filtering is the most common process in collections. In Koltin, filtering is defined by a predicate, where a predicate represents a lambda function that takes collection elements and returns a boolean value 'true', meaning that the given element matches the predicate. Otherwise false.

Syntax

Following is the syntax of Kotlin list filter() function −

list.filter { predicate }

Parameters

This function accepts lambda function to define a logic to filter.

Return value

This function returns a new list containing only those elements that satisfy the predicate.

Example 1: Filter Even Number

Let's see a basic example of the filter() function, which return a list containing only even number −

fun main(args: Array<String>) {
   val numbers = listOf(2, 3, 4, 6, 7, 10)
   println(numbers.filter{ it % 2 == 0})
}

Output

Following is the output −

[2, 4, 6, 10]

Example 2: Filter String by Length

In the following example, we use the filter() to filter the string from the list that has a length less than 5 −

fun main(args: Array<String>){
   val words = listOf("Kotlin", "Java", "C++", "Python")
   val shortWords = words.filter { it.length <= 4 }
   println(shortWords)
}

Output

Following is the output −

[Java, C++]

Example 3: Filter Using a Custom Function

This is another example of the filter() function. Here, we create a custom function to filter the number which is greater than 0 −

// create a custom function
fun isPositive(number: Int): Boolean = number > 0
fun main(args: Array<String>){
   val numbers = listOf(-3, 0, 2, 5, -1)
   val positiveNumbers = numbers.filter(::isPositive)
   println(positiveNumbers)
}

Output

Following is the output −

[2, 5]
kotlin_lists.htm
Advertisements