Kotlin·Kotlin from syntax to a coroutine app

Collections

Work with lists, sets, maps and functional operations.

Beginner 13 min read Lesson 4 of 300 Challenge included
What you will be able to do
  • Prefer listOf and mapOf for read-only data.
  • Use map and filter for transformations.
  • Use groupBy for grouping.
  • Use associateBy to index by a key.

In plain English

Kotlin separates read-only and mutable collection interfaces. Use map, filter, groupBy and associate to transform data. Read-only is the default; expose mutable state only where needed.

Collections.ktKotlin
data class Lesson(val title: String, val minutes: Int)

fun main() {
    val lessons = listOf(Lesson("HTML", 12), Lesson("CSS", 18), Lesson("SQL", 9))
    val long = lessons.filter { it.minutes >= 12 }.map { it.title }
    val total = lessons.sumOf { it.minutes }
    println(long)
    println(total)
}
Your turn

Filter and map

Easy

Return the titles of lessons with at least 12 minutes.

KOTLIN · starter
lessons
Check your understanding before moving on.
Knowledge checkQuestion 1

Which function groups elements by a key?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 4 of 300 · 0% of course