Kotlin List filterNotNull()
Syntax & Examples


Syntax of List.filterNotNull()

The syntax of List.filterNotNull() extension function is:

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

This filterNotNull() extension function of List returns a list containing all elements that are not null.



✐ Examples

1 Example

In this example,

  • We create a list named list containing integers and null values.
  • We apply the filterNotNull extension function on list to filter out all the non-null elements.
  • The filtered elements are stored in the result list.
  • Finally, we print the result list to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, null, 3, null, 5);
    val result = list.filterNotNull();
    println(result);
}

Output

[1, 3, 5]

2 Example

In this example,

  • We create a list named list containing characters and null values.
  • We apply the filterNotNull extension function on list to filter out all the non-null elements.
  • The filtered elements are stored in the result list.
  • Finally, we print the result list to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', null, 'b', null, 'c');
    val result = list.filterNotNull();
    println(result);
}

Output

[a, b, c]

3 Example

In this example,

  • We create a list named list containing strings and null values.
  • We apply the filterNotNull extension function on list to filter out all the non-null elements.
  • The filtered elements are stored in the result list.
  • Finally, we print the result list to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", null, "banana", null, "orange");
    val result = list.filterNotNull();
    println(result);
}

Output

[apple, banana, orange]

Summary

In this Kotlin tutorial, we learned about filterNotNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.