Welcome to this comprehensive guide on using the filter and map functions in Kotlin! These are essential tools for data manipulation that every programmer should know. Let's dive in!
In this lesson, we will learn about two powerful functions in Kotlin: filter and map. They are fundamental for filtering and transforming data, making them crucial for real-world projects.
filter function? 📝The filter function in Kotlin allows you to create a new collection containing only the elements that satisfy a specific condition.
Simple Example:
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }In the above example, we have a list of numbers. The filter function creates a new list containing only the even numbers from the original list.
map function? 📝The map function in Kotlin transforms each element of a collection into a new form.
Simple Example:
val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }In the above example, we have a list of numbers. The map function creates a new list containing the squares of the original numbers.
filter and map together 💡You can use filter and map together to transform your data in multiple steps.
Example:
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val squaredEvenNumbers = numbers
.filter { it % 2 == 0 }
.map { it * it }In this example, we first filter out the even numbers, and then square them.
Let's consider a list of users with their names and ages:
val users = listOf(
User("John", 25),
User("Mary", 30),
User("David", 20),
User("Sarah", 19),
User("James", 27)
)We can filter out users who are younger than 25:
val youngUsers = users.filter { it.age < 25 }You can map a list of strings to their uppercase versions:
val words = listOf("hello", "world", "Kotlin")
val uppercaseWords = words.map { it.toUpperCase() }Given a list of numbers, how can you create a new list containing the squares of the odd numbers?