CodeBlanks Logo Icon CodeBlanks

Collections

Write data management with List and Map.

List operations: filter

On Kotlin lists filter keeps the elements that match a condition. It is ideal for separating done and pending tasks.

val done = tasks.filter { it.done }
val pending = tasks.filter { !it.done }

it stands for each element in the list. Elements whose condition returns true stay in the result. This builds a sublist in one line.

forEach and count

forEach runs a block for each element in the list. count returns the number of elements. Both are handy list tools.

tasks.forEach { println(it) }
val n = tasks.count()

forEach acts like a loop but is more concise. count gives the size; it can also take a condition: tasks.count { it.done }. This lets you walk and summarise the list.

Practice Filter done tasks and print them

Add a fun listDone() = tasks.filter { it.done } method to the TaskList class. In main add two tasks, complete the first with list.tasks[0].done = true, then print list.listDone() with println.

Starter code

Main.kt
class Task(val title: String) {
    var done: Boolean = false
    override fun toString(): String {
        return if (done) "[x] $title" else "[ ] $title"
    }
}

class TaskList {
    val tasks = mutableListOf<Task>()
    fun addTask(title: String) {
        tasks.add(Task(title))
    }
    // listDone metodunu buraya yaz
}

fun main() {
    val list = TaskList()
    // Add two tasks; mark one done; print the done ones
}

Sample solution

Main.kt
class Task(val title: String) {
    var done: Boolean = false
    override fun toString(): String {
        return if (done) "[x] $title" else "[ ] $title"
    }
}

class TaskList {
    val tasks = mutableListOf<Task>()
    fun addTask(title: String) {
        tasks.add(Task(title))
    }
    fun listDone() = tasks.filter { it.done }
}

fun main() {
    val list = TaskList()
    list.addTask("Study Kotlin")
    list.addTask("Shopping")
    list.tasks[0].done = true
    println(list.listDone())
}

Expected output

[[x] Kotlin çalış]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does filter do?

  • Gives a subset matching a condition Correct answer
  • Returns all elements
  • Sorts the list
  • Returns the first element

Explanation: filter keeps the elements matching a condition.

2 Fill in the blank: filter done tasks

Question
val done = tasks.____ { it.done }
Answer
val done = tasks.filter { it.done }

Explanation: filter { it.done } returns completed tasks.

3 Match operation to use

Term Meaning
filter Filter by condition
forEach Do for each
count Count
find Find first

All lessons in Beginner