Skip to main content

Collections and Stream Operations

Functional programming is a coding paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. In functional programming, functions are first-class citizens. This means they can be passed as arguments to other functions, returned as values from other functions, or assigned to variables. Kotlin, as a statically typed programming language, supports this functional style of programming.

In this tutorial, we will explore one of the most important features of functional programming in Kotlin - Collections and Stream Operations. Collections are a group of similar items, and stream operations allow you to manipulate these collections in a functional manner.

Collections in Kotlin

A collection is a group of items stored in a single unit. Kotlin provides a rich set of collection interfaces, such as List, Set, and Map, and their mutable versions MutableList, MutableSet, and MutableMap.

val list = listOf(1, 2, 3, 4, 5)
val set = setOf(1, 2, 3, 3, 3)
val map = mapOf("one" to 1, "two" to 2, "three" to 3)

Stream Operations in Kotlin

Stream operations, also known as collection pipelines, are a sequence of operations that transform a collection into a result. They have two types of operations:

  • Intermediate operations: They transform a stream into another stream, such as filter and map.
  • Terminal operations: They complete the pipeline and return a result, such as reduce, find, match, and so on.

Filter and Map

Filter and map are two of the most commonly used intermediate operations. The filter function is used to filter collections based on a certain condition. The map function is used to transform the elements of the collection.

val numbers = listOf(1, 2, 3, 4, 5, 6)
val evenNumbers = numbers.filter { it % 2 == 0 }
val squares = numbers.map { it * it }

Reduce

Reduce is a terminal operation that combines all elements of a collection into a single result.

val numbers = listOf(1, 2, 3, 4, 5, 6)
val sum = numbers.reduce { acc, i -> acc + i }

Conclusion

In this tutorial, we have seen how to use collections and stream operations in Kotlin. These are powerful tools that allow you to write expressive, efficient, and safe code in a functional style. Remember, functional programming is all about transforming data, and collections and stream operations are the main tools for this in Kotlin.

So, keep practicing and exploring more about these concepts, as they form the backbone of functional programming in Kotlin.