The mapNotNull function in Kotlin is used to transform elements of a collection by applying a given function to each element and returning a new list containing only the non-null results of the transformation. This function is part of the Kotlin standard library and is useful when you want to filter out null values from the transformation results.
Table of Contents
- Introduction
mapNotNullFunction Syntax- Understanding
mapNotNull - Examples
- Basic Usage
- Mapping a List of Strings
- Mapping with Custom Transformations
- Real-World Use Case
- Conclusion
Introduction
The mapNotNull function allows you to transform elements of a collection (such as a list) by applying a given function to each element and creating a new list that includes only the non-null results. This is useful for scenarios where you need to perform operations on each element and exclude any null results from the final list.
mapNotNull Function Syntax
The syntax for the mapNotNull function is as follows:
fun <T, R : Any> Iterable<T>.mapNotNull(transform: (T) -> R?): List<R>
Parameters:
transform: A lambda function that takes an element of the original collection as input and returns a transformed value, which can be null.
Returns:
- A new list containing only the non-null results of applying the transformation function to each element of the original collection.
Understanding mapNotNull
The mapNotNull function iterates over each element in the original collection, applies the given transformation function to it, and collects the non-null results in a new list. This allows you to perform operations on each element and filter out null results in one step.
Examples
Basic Usage
To demonstrate the basic usage of mapNotNull, we will transform a list of strings by converting them to integers and excluding any null results.
Example
fun main() {
val strings = listOf("1", "2", "three", "4", "five")
val numbers = strings.mapNotNull { it.toIntOrNull() }
println("Numbers: $numbers")
}
Output:
Numbers: [1, 2, 4]
Mapping a List of Strings
This example shows how to use mapNotNull to transform a list of strings by converting each string to its length and excluding null results.
Example
fun main() {
val fruits = listOf("apple", "banana", null, "cherry", "")
val lengths = fruits.mapNotNull { it?.length }
println("Lengths: $lengths")
}
Output:
Lengths: [5, 6, 6, 0]
Mapping with Custom Transformations
This example demonstrates how to use mapNotNull with custom transformation functions to create a list of objects.
Example
data class Person(val name: String, val age: Int)
fun main() {
val names = listOf("Alice", null, "Bob", "Charlie", null)
val people = names.mapNotNull { name -> name?.let { Person(it, it.length * 5) } }
println("People: $people")
}
Output:
People: [Person(name=Alice, age=25), Person(name=Bob, age=15), Person(name=Charlie, age=35)]
Real-World Use Case
Transforming and Filtering User Input
In real-world applications, the mapNotNull function can be used to transform and filter user input, ensuring that only valid, non-null results are included in the final list.
Example
data class User(val id: Int, val name: String)
fun main() {
val inputs: List<String?> = listOf("1:Alice", "2:Bob", null, "invalid", "3:Charlie")
val users = inputs.mapNotNull { input ->
input?.split(":")?.takeIf { it.size == 2 }?.let { (id, name) ->
id.toIntOrNull()?.let { User(it, name) }
}
}
println("Users: $users")
}
Output:
Users: [User(id=1, name=Alice), User(id=2, name=Bob), User(id=3, name=Charlie)]
Conclusion
The mapNotNull function in Kotlin is a powerful and convenient way to transform elements of a collection and filter out null results in one step. It allows you to create a new list containing only the non-null results of the transformation, making it useful for various applications, including data processing, transformation, and validation. By understanding and using the mapNotNull function, you can effectively manage and process collections in your Kotlin applications.