6 Working with collections and sequences

 

This chapter covers

  • Working with collections in a functional style
  • Sequences: performing collection operations lazily

In chapter 5, you learned about lambdas as a way of passing small blocks of code to other functions. One of the most common uses for lambdas is working with collections. In this chapter, you will see how replacing common collection access patterns with a combination of standard library functions and your own lambdas can make your code more expressive, elegant, and concise—whether you are filtering your data based on predicates, need to group data, or want to transform collection items from one form to another.

You will also explore sequences as an alternative way to apply multiple collection operations efficiently and without creating much overhead. You will learn the difference between eager and lazy execution of collection operations in Kotlin and how to use either one in your programs.

6.1 Functional APIs for collections

A functional programming style provides many benefits when it comes to manipulating collections. For most tasks, you can use functions provided by the standard library and customize their behavior by passing lambdas as arguments to these functions. Compared to navigating through collections and aggregating data manually, this allows you to express common operations consistently, using a vocabulary of functions you share with other Kotlin developers.

6.1.1 Removing and transforming elements: filter and map

6.1.2 Accumulating values for collections: reduce and fold

6.1.3 Applying a predicate to a collection: all, any, none, count, and find

6.1.4 Splitting a list into a pair of lists: partition

6.1.5 Converting a list to a map of groups: groupBy

6.1.6 Transforming collections into maps: associate, associateWith, and associateBy

6.1.7 Replacing elements in mutable collections: replaceAll and fill

6.1.8 Handling special cases for collections: ifEmpty

6.1.9 Splitting collections: chunked and windowed

6.1.10 Merging collections: zip

6.1.11 Processing elements in nested collections: flatMap and flatten

6.2 Lazy collection operations: Sequences

6.2.1 Executing sequence operations: Intermediate and terminal operations