1. Introduction

Often, when working with lists in Kotlin, it’s necessary to remove null and empty values. Null values can cause errors in our code, while empty values can add unnecessary bloat to our list.

In this tutorial, we’ll explore various ways to remove null and empty values from a List in Kotlin.

2. Using Simple List Iteration

The first approach we’ll use is the programmatic approach. It involves iterating over the list and removing all null and empty elements in the process:

fun removeValuesViaIteration(listWithNullsAndEmpty: MutableList<String?>): List<String> {
    val iterator = listWithNullsAndEmpty.iterator()
    while (iterator.hasNext()) {
        val element = iterator.next()
        if (element == null || element.isEmpty()) {
            iterator.remove()
        }
    }
    return listWithNullsAndEmpty as List<String>
}

The method above accepts a MutableList that possibly contains null and empty values. Once we pass this list to our removeValuesViaIteration() method, we then create an Iterator for the list to iterate over each element in the list.

In each iteration, we check if the current element is null or empty. If it is, we remove this element from the list using the iterator’s remove() function. Finally, we return the same list after iterating through it completely. Note that we can cast the result since the nulls have been removed.

Let’s write a test to be sure our method functions correctly:

@Test
fun `remove null and empty values from list via list iteration`() {
    val listWithNullsAndEmpty: MutableList<String?> = mutableListOf("A", null, "", "C", null, "E")
    val listWithoutNullsAndEmpty = removeValuesViaIteration(listWithNullsAndEmpty)
    assertEquals(listOf("A", "C", "E"), listWithoutNullsAndEmpty)
}

3. Using the filterNotNull() and filterNot() Methods

Another way to get rid of empty and null values from a List is by leveraging the filterNotNull() and filterNot() methods. The filterNotNull() method returns a new list that contains only non-null elements from the original list:

val listWithNulls: List<String?> = listOf("A", null, "", "C", null, "E")
val listWithoutNulls: List<String> = listWithNulls.filterNotNull()

This code snippet shows how we can use the filterNotNull() method on a List to remove all null values in just a single line of code. So, by calling this method on our list, we end up with a new list with values [“A”, “”, “C”, “E”].

Similarly, the filterNot() method comes in handy for removing all empty values from the list. The filterNot() method takes a lambda predicate function as an argument and returns a new list containing only the elements for which the predicate returns false.

Let’s also demonstrate the use of the filterNot() method:

val listWithEmpty: List<String> = listOf("A", "", "C", "E")
val listWithoutEmpty: List<String> = listWithEmpty.filterNot { it.isEmpty() }

Putting all this together, we can achieve our goal by calling these two methods in succession:

@Test
fun `remove null and empty values from list using filterNotNull and filterNot methods`() {
    val listWithNullsAndEmpty: List<String?> = listOf("A", null, "", "C", null, "E")
    val listWithoutNulls: List<String> = listWithNullsAndEmpty.filterNotNull()

    val listWithoutNullsAndEmpty: List<String> = listWithoutNulls.filterNot { it.isEmpty() }

    assertEquals(listOf("A", "", "C", "E"), listWithoutNulls)
    assertEquals(listOf("A", "C", "E"), listWithoutNullsAndEmpty)
}

Here, we create a list containing both null and empty values. We then call this list’s filterNotNull() method to obtain a list containing only non-null values, as seen in the first assertion. Subsequently, we call the filterNot() method on the list we obtained from calling the filterNotNull() method, thus obtaining our final list without null and empty values.

4. Using the removeIf() Method

The previous approach we explored ultimately creates a new list. However, if we have a MutableList, we can instead get rid of all null and empty values in place by using the removeIf() method. Similarly, this method accepts a predicate as an argument and removes all elements for which the predicate returns true:

val listWithNullsAndEmpty: MutableList<String?> = mutableListOf("A", null, "", "C", null, "E")
listWithNullsAndEmpty.removeIf { it == null || it.isEmpty() }

Having created a MutableList containing both null and empty values, we use the removeIf() method to remove these values from the list all at once. The resulting list from our example is [“A”, “C”, “E”].

Finally, we’ll also test the above code to ensure it works as expected:

@Test
fun `remove null and empty values from list using removeIf method`() {
    val listWithNullsAndEmpty: MutableList<String?> = mutableListOf("A", null, "", "C", null, "E")
    listWithNullsAndEmpty.removeIf { it == null || it.isEmpty() }

    assertEquals(listOf("A", "C", "E"), listWithNullsAndEmpty)
}

5. Conclusion

This article explored ways to remove null and empty values from a List in Kotlin. First, we discussed the programmatic approach involving iterating a list and removing any null or empty elements. Next, we saw how to use built-in methods to achieve the same goal.

Remember that while the removeIf() method eliminates all null and empty values in place, the use of the filterNotNull() and filterNot() methods each return a new list.

As always, the code used in this article is available over on GitHub.
Comments are closed on this article!