Kotlin Array - filterNotNull() Function



The Kotlin array filterNotNull() function is used to create a new list containing all elements that are not null. This means; this function filters out the null element and returns all elements as a list.

Syntax

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

fun <T : Any> Array<out T?>.filterNotNull(): List<T>

Parameters

This function does not accepts any parameters.

Return value

This function returns a list containing all elements except null.

Example 1

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

fun main(args: Array&l;tString>) {
   val number: Array&l;tInt?> = arrayOf(1, 2, 3, 4, null, 5, null)
   val list = number.filterNotNull()
   println("Not filtered list: $list")
}

Output

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

Not filtered list: [1, 2, 3, 4, 5]

Example 2

The example below creates an array that stores strings. We then use the filterNotNull() function to print list containing all elements except null −

fun main(args: Array<String>) {
   val strings: Array<String?> = arrayOf(null, "Hello", null, "tutorix", "tutorialspoint")
   val filterNotNull = strings.filterNotNull()
   println("list: $filterNotNull")
}

Output

The above code produce following output −

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