Sling Academy
Home/Kotlin/Filtering Non-Null Values from Lists with `filterNotNull` in Kotlin

Filtering Non-Null Values from Lists with `filterNotNull` in Kotlin

Last updated: December 05, 2024

Kotlin is a statically-typed, modern programming language developed by JetBrains, and since its inception, it has gained significant popularity. One of the features that makes Kotlin so appealing is its rich set of standard library functions that improve code readability and efficiency. Among these, filterNotNull is particularly useful for handling collections containing nullable values. In this article, we will explore the filterNotNull function, understand how it works, and boost your Kotlin coding skills with practical examples.

What is filterNotNull?

In Kotlin, filterNotNull is an extension function for collections, specifically designed to filter out null values, providing only non-null elements from a collection. It's particularly useful when dealing with lists or arrays that may contain nulls, avoiding the dreaded null-pointer exceptions that many developers have faced, especially those transitioning from Java.

Using filterNotNull on a List

Let's start with a simple example of a list of nullable integers. Suppose we have a list of integers, some of which might be null. Here's how you can use filterNotNull to efficiently create a new list without nulls:

val listWithNulls: List = listOf(1, 2, null, 4, null, 6)
val listWithoutNulls: List = listWithNulls.filterNotNull()

println(listWithoutNulls) // Output: [1, 2, 4, 6]

In this snippet, listWithNulls contains some integer values and null values. By invoking filterNotNull(), we derive listWithoutNulls, which is a List<Int> containing only the non-null values.

Using filterNotNull with Other Data Types

filterNotNull isn’t limited to integer lists. You can use it with any collection type, including lists of strings, objects, and even arrays. Let’s see an example involving strings:

val stringList: List = listOf("Kotlin", null, "Java", null, "Python")
val nonNullStringList: List = stringList.filterNotNull()

println(nonNullStringList) // Output: ["Kotlin", "Java", "Python"]

Here, filterNotNull effectively removes the null entries from stringList.

Benefits of Using filterNotNull

  • Improves Readability: Instead of manually iterating through collections to remove nulls, filterNotNull achieves this in a single, readable line of code.
  • Reduces Errors: By handling null values effectively, it minimizes the chance of encountering null-pointer exceptions during runtime.
  • Easy to Use: As an extension function, it can be appended directly to any nullable collection, making it intuitive and easy to integrate into existing codebases.

Practical Example: Filtering a List of Custom Objects

Consider a scenario where you have a list of nullable custom objects, for instance, a Person class:

data class Person(val name: String, val age: Int)

val people: List = listOf(
    Person("Alice", 30),
    null,
    Person("Bob", 25),
    null,
    Person("Charlie", 35)
)
val presentPeople: List = people.filterNotNull()

println(presentPeople) // Output: [Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]

In this example, we filter out all null persons, retaining a list only of the non-null Person objects.

Conclusion

Kotlin’s filterNotNull function is a powerful tool when dealing with nullable collections. It simplifies the process of filtering non-null values, thereby enhancing your code’s safety and readability. By harnessing filterNotNull, you can write more robust and cleaner Kotlin applications.

As you continue to explore Kotlin, practice using filterNotNull in various scenarios, and you’ll gradually see improvements in how you handle null safety within your projects.

Next Article: Using the `?:` Elvis Operator for Lazy Initialization in Kotlin

Previous Article: Combining Safe Calls with Collections in Kotlin

Series: Null Safety in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin