Kotlin – Filter Array

Filter Array in Kotlin

To filter the elements of a given Array based on a condition in Kotlin, you can use Array.filter() function.

Call the filter() function on the given Array object, and pass the predicate to the function.

arr.filter { predicate }

For example to filter the string elements of given Array whose length is greater than five, the filter() function with the predicate would be as shown in the following.

arr.filter { it.length >5 }
Input Array
["apple", "kiwi", "banana", "cherry", "fig"]

Output Array
["banana", "cherry"]

The filter() function returns a List. You may convert this to an Array using List.toTypedArray() function.

Examples

Filter string Array based on string length

In the following program, we take an Array of strings in arr, and filter the elements based on length. Only those string elements whose length is greater than five will pass through the filter and make to the result.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf("apple", "kiwi", "banana", "cherry", "fig")
    val filteredArray = arr.filter { it.length > 5 }.toTypedArray()
    println(filteredArray.contentToString())
}

Output

[banana, cherry]

Explanation

Input Array
["apple", "kiwi", "banana", "cherry", "fig"]

String lengths
 5         4       6         6         3

Elements that pass the filter (length > 5)
                  "banana"  "cherry"

Output Array
["banana", "cherry"]

Filter Integer Array

In the following program, we take an Array of integers in arr, and filter only positive values.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf(5, -8, -2, 7, 0, 6, -31, 14)
    val filteredArray = arr.filter { it >= 0 }.toTypedArray()
    println(filteredArray.contentToString())
}

Output

[5, 7, 0, 6, 14]