0
0
Kotlinprogramming~5 mins

Terminal operations trigger execution in Kotlin

Choose your learning style9 modes available
Introduction

Terminal operations start the actual work on data collections. Without them, nothing happens.

When you want to get a final result from a list, like counting items.
When you want to print or save the processed data.
When you want to check if any item matches a condition.
When you want to collect filtered or mapped data into a new list.
Syntax
Kotlin
collection.terminalOperation()

Terminal operations include functions like toList(), count(), forEach(), any(), and reduce().

They cause the lazy operations before them to run and produce results.

Examples
Counts how many items are in the list.
Kotlin
val count = listOf(1, 2, 3).count()
Prints each item, triggering execution.
Kotlin
listOf(1, 2, 3).forEach { println(it) }
Checks if any number is even.
Kotlin
val anyEven = listOf(1, 2, 3).any { it % 2 == 0 }
Sample Program

This example doubles numbers, filters those greater than 5, then collects them into a list. The toList() call triggers the work.

Kotlin
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.asSequence()
    .map { it * 2 }  // lazy operation
    .filter { it > 5 }  // lazy operation

val result = doubled.toList()  // terminal operation triggers execution
println(result)
OutputSuccess
Important Notes

Without a terminal operation, lazy operations like map and filter do not run.

Terminal operations produce a result or side effect, like printing or collecting data.

Summary

Terminal operations start the actual processing of data.

They produce results or side effects.

Common terminal operations include toList(), count(), and forEach().