Kotlin Array.filter() function
In Kotlin, the Array.filter()
function is used to create a new array containing only the elements that satisfy a given predicate. It allows you to filter elements based on a condition and create a subset of the original array.
This function is helpful when you want to selectively include or exclude elements from an array based on a specified criterion.
In this tutorial, we’ll explore the syntax of the Array.filter()
function and provide examples of its usage with Kotlin Array.
Syntax
The syntax of the Array.filter()
function is as follows:
inline fun <T> Array<out T>.filter(
predicate: (T) -> Boolean
): List<T>
where
Parameter | Description |
---|---|
predicate | A lambda function that takes an element from the array and returns true or false based on the condition to be satisfied. |
The Array.filter()
function returns a List object.
Examples for Array filter() function
1. Filtering Even Numbers
In this example, we’ll use filter()
to obtain a new array containing only the even numbers from the given array of integers numbersArray
.
The predicate for the filter()
function shall to be the condition to check if number is even.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
// Filtering even numbers from the array
val evenNumbers = numbersArray.filter { it % 2 == 0 }
// Printing the original array aand the result
println("Numbers Array\n${numbersArray.joinToString(", ")}\n")
println("Even Numbers\n${evenNumbers.joinToString(", ")}")
}
Output
Numbers Array
1, 2, 3, 4, 5, 6, 7, 8, 9
Even Numbers
2, 4, 6, 8
2. Filtering Strings by Length
In this example, we’ll use filter()
to obtain a new array containing only the strings with a length greater than 5
from the given array of strings wordsArray
.
The predicate for filter()
function shall be the condition to check if the length of string element is greater than 5
.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "orange", "kiwi", "grape")
// Filtering strings with length greater than 5
val longWords = wordsArray.filter { it.length > 5 }
// Printing the original array and the result
println("Words Array\n${wordsArray.joinToString(", ")}\n")
println("Long Words\n${longWords.joinToString(", ")}")
}
Output
Words Array
apple, banana, orange, kiwi, grape
Long Words
banana, orange
Summary
In this tutorial, we’ve covered the filter()
function of Kotlin Array, its syntax, and how to use it to create a new array containing elements that satisfy a specified condition.