Kotlin Array - filter() Function



The Kotlin array filter() function is used to create a new list after an existing collection has been filtered. Takes a predicate as an argument and returns only items that satisfy the specified conditions.

If an element meets this condition, it will be added to the newly created list. Otherwise it is discarded from the final list.

Syntax

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

fun <T> Array<out T>.filter(predicate: (T) -> Boolean): List<T>

Parameters

This function accepts a predicate as a parameter. Predicate represent a condition which gives boolean value.

Return value

This function returns a list containing all filtered elements.

Example 1

Following is the basic example to demonstrate the use of filter() function −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val list = number.filter{it>3}
   println("Filtered list: $list")
}

Output

On execution of the above code we get the following result −

Filtered list: [4, 5, 6, 7, 8]

Example 2

Now, let's see another example. Here, we use the filter() function to filter out all the even number from an array −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val list = number.filter{it%2==0}
   println("Even number: $list")
}

Output

After execution of the above code we get the following output −

Filtered list: [2, 4, 6, 8]

Example 3

The example below creates an array that stores strings. We then use the filter() function to display the elements whose length is more than three −

fun main(args: Array<String>) {
   val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint")
   val filter = strings.filter{it.length>3}
   println("list: $filter")
}

Output

The above code produce following output −

list : [Hello, tutorix, tutorialspoint]
kotlin_arrays.htm
Advertisements