Kotlin Filter and Map: Powerful Tools for Data Manipulation

beginner
14 min

Kotlin Filter and Map: Powerful Tools for Data Manipulation

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!

Introduction 🎯

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.

What is the 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:

kotlin
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.

What is the map function? 📝

The map function in Kotlin transforms each element of a collection into a new form.

Simple Example:

kotlin
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.

Using filter and map together 💡

You can use filter and map together to transform your data in multiple steps.

Example:

kotlin
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.

Advanced Examples 🎯

Filtering a List of Users

Let's consider a list of users with their names and ages:

kotlin
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:

kotlin
val youngUsers = users.filter { it.age < 25 }

Mapping a List of Strings to Uppercase

You can map a list of strings to their uppercase versions:

kotlin
val words = listOf("hello", "world", "Kotlin") val uppercaseWords = words.map { it.toUpperCase() }

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Given a list of numbers, how can you create a new list containing the squares of the odd numbers?