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…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Explains 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, 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.

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

  1. 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]

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

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help