Skip to main content

How to remove null elements from an array in Kotlin

How to remove null elements from an array in Kotlin.

Here's a step-by-step tutorial on how to remove null elements from an array in Kotlin:

Step 1: Create an array with null elements

First, let's create an array that contains null elements. This will serve as our starting point for the tutorial. Here's an example:

val array = arrayOf("Hello", null, "World", null, "Kotlin", null)

Step 2: Use filterNotNull() function

Kotlin provides a built-in function called filterNotNull() that allows us to remove null elements from an array. This function returns a new array that contains only the non-null elements. Here's how you can use it:

val newArray = array.filterNotNull()

In the above code, filterNotNull() is called on the array and the result is assigned to a new array called newArray.

Step 3: Print the result

Finally, let's print the contents of the new array to verify that the null elements have been removed. Here's an example:

newArray.forEach { println(it) }

In the above code, forEach() function is called on the newArray and a lambda expression is used to print each element of the array.

Complete code example:

fun main() {
val array = arrayOf("Hello", null, "World", null, "Kotlin", null)
val newArray = array.filterNotNull()
newArray.forEach { println(it) }
}

When you run the above code, the output will be:

Hello
World
Kotlin

Alternate Approach: Using a for loop If you prefer using a for loop instead of the filterNotNull() function, here's an alternate approach:

val newArray = mutableListOf<String>()
for (element in array) {
if (element != null) {
newArray.add(element)
}
}

In this approach, we create a new mutable list called newArray. Then, we iterate over each element in the original array using a for loop. If an element is not null, we add it to the newArray.

Complete code example using a for loop:

fun main() {
val array = arrayOf("Hello", null, "World", null, "Kotlin", null)
val newArray = mutableListOf<String>()
for (element in array) {
if (element != null) {
newArray.add(element)
}
}
newArray.forEach { println(it) }
}

This will produce the same output as the previous example:

Hello
World
Kotlin

That's it! You have successfully removed null elements from an array in Kotlin using both the filterNotNull() function and a for loop.