Goal: This tutorial aims to guide you through the process of filtering and transforming collections in Kotlin. We will explore the built-in functions that Kotlin provides to accomplish these tasks.
What You Will Learn: By the end of this tutorial, you will understand how to filter and transform collections in Kotlin using the filter
, map
, flatMap
, mapNotNull
functions, and others.
Prerequisites: You should have a basic understanding of Kotlin programming, including its syntax and fundamental concepts such as variables, functions, and collections.
Filtering is the process of selecting elements from a collection that satisfy a certain condition. In Kotlin, this is done using the filter
function.
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
In this example, it
refers to the current element being processed. The code inside the curly braces ({}
) is the condition for filtering: in this case, we are selecting only those numbers that are even.
Transforming, or mapping, is the process of creating a new collection from an existing one, where each element of the new collection is the result of applying a function to each element of the original collection. This is done using the map
function.
val numbers = listOf(1, 2, 3, 4, 5)
val squares = numbers.map { it * it }
In this example, we are creating a new list, squares
, where each element is the square of the corresponding element in the original list, numbers
.
val numbers = listOf(1, -2, 3, -4, 5)
val positiveNumbers = numbers.filter { it > 0 } // filtering positive numbers
println(positiveNumbers) // Expected output: [1, 3, 5]
val numbers = listOf(1, 2, 3, 4, 5)
val doubledNumbers = numbers.map { it * 2 } // mapping each number to its double
println(doubledNumbers) // Expected output: [2, 4, 6, 8, 10]
Today, we learned about how to filter and transform collections in Kotlin. We used the filter
function to select elements from a collection that satisfy a certain condition, and the map
function to create a new collection by applying a function to each element of the original collection.
Next, you can explore more advanced collection processing functions, such as reduce
, fold
, groupBy
, and others. We recommend visiting the Kotlin documentation for more detailed information.
Solution:
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.filter { it % 2 == 0 }.map { it * it }
println(result) // Expected output: [4, 16]
Solution:
kotlin
val words = listOf("apple", "banana", "avocado", "cherry", "apricot")
val result = words.filter { it.startsWith("a") }.map { it.length }
println(result) // Expected output: [5, 7, 7]
Remember to practice regularly to improve your skills. Happy coding!