Kotlin Collections: map, filter, reduce and More

Introduction

Kotlin collections provide powerful functions that allow developers to write concise and expressive code.

Instead of writing long loops, Kotlin lets you perform complex operations with simple and readable functions.

If you're developing Android apps with Kotlin, you'll frequently use collection functions such as:

  • map

  • filter

  • reduce

  • forEach

  • groupBy

This guide provides a quick Kotlin collections cheat sheet with practical examples you can use in real projects.

๐Ÿ‘‰ Developer Tip

Most experienced Kotlin developers rely heavily on these collection functions because they make code shorter and easier to maintain.

Kotlin Collections Overview

Collections in Kotlin allow you to work with groups of data such as:

  • Lists

  • Sets

  • Maps

Example list:

val numbers = listOf(1,2,3,4,5)

From here, Kotlin provides many useful functions to transform or process the data.

ย 

map Function

The map function transforms each element in a collection.

Example:

val numbers = listOf(1,2,3)

val doubled = numbers.map {
it * 2
}

Result:

[2,4,6]

ย 

filter Function

The filter function selects elements that match a condition.

Example:

val numbers = listOf(1,2,3,4,5)

val evenNumbers = numbers.filter {
it % 2 == 0
}

Result

[2,4]

forEach Function

forEach is used to iterate through elements.

Example:

numbers.forEach {
println(it)
}

Developer insight

Use forEach when you need to perform an action on every element.

reduce Function

reduce combines elements into a single result.

Example:

val numbers = listOf(1,2,3,4)

val sum = numbers.reduce { acc, i ->
acc + i
}

Result

10

ย 

groupBy Function

groupBy groups elements based on a condition.

Example:

val numbers = listOf(1,2,3,4,5)

val grouped = numbers.groupBy {
it % 2 == 0
}

Result

{false=[1,3,5], true=[2,4]}

Quick Cheat Sheet

Function Purpose
map transform elements
filter select elements
forEach iterate elements
reduce combine values
groupBy group elements

ย 

heejin's picture

Language

Get in touch with us

"If you would thoroughly know anything, teach it to other."
- Tryon Edwards -