Kotlin / Collections and Generics
Filtering and Transforming Collections
This tutorial will guide you through filtering and transforming collections in Kotlin. These operations are crucial for efficiently processing data, and you'll learn how to use th…
Section overview
5 resourcesExplains how to use Kotlin’s collection framework and work with generics.
Filtering and Transforming Collections in Kotlin
1. Introduction
-
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,mapNotNullfunctions, and others. -
Prerequisites: You should have a basic understanding of Kotlin programming, including its syntax and fundamental concepts such as variables, functions, and collections.
2. Step-by-Step Guide
Filtering 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 Collections
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.
3. Code Examples
Example 1: Filtering Collection
val numbers = listOf(1, -2, 3, -4, 5)
val positiveNumbers = numbers.filter { it > 0 } // filtering positive numbers
println(positiveNumbers) // Expected output: [1, 3, 5]
Example 2: Mapping Collection
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]
4. Summary
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.
5. Practice Exercises
- Exercise 1: Given a list of numbers, filter out the odd numbers and map the remaining even numbers to their squares.
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]
- Exercise 2: Given a list of strings, create a new list that contains the lengths of each string, but only for strings that start with the letter 'a'.
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!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article