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’re filtering your data based on predicates, need to group data, or 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.
A functional programming style provides many benefits when it comes to manipulating collections. For the majority of tasks, you can use functions provided by the standard library, and customize their behaviour by passing lambdas as arguments to these functions. Compared to navigating through collections and aggregating data manually, this allows you to express common operations consistenly using a vocabulary of functions that you share with other Kotlin developers.