Internal Iterators
We'll cover the following
We mostly use for
to program external iterators. But internal iteration involves many specialized tools like filter()
, map()
, flatMap()
, reduce()
, and so on. Much like the way a professional mechanic uses different specialized tools to fix a car, and doesn’t settle for just a hammer, in functional programming we use a combination of the right tools for different tasks. The Kotlin standard library provides plenty of higher-order functions for internal iteration. We’ll visit some of the most commonly used functions.
filter, map, and reduce
filter()
, map()
, and reduce()
are the three amigos of functional programming; they are fundamental functions used as internal iterators. The filter()
function picks certain values from a given collection while dropping the others. The map()
function transforms the values in a collection using a given function or lambda. Finally, the reduce()
function performs a cumulative operation on the elements, often to arrive at a single value. All these functions perform their operations without mutating or changing the given collection—they return a copy with the appropriate values.
The size of the collection returned by filter()
may vary from 0
to n
where n
is the number of elements in the original collection. The result is a sub-collection; that is, the values in the output collection are values present in the original collection. The lambda passed to filter()
is applied on each element in the original collection. If and only if the lambda returns true
, when evaluated for an element, the element from the original collection is included in the output collection.
The size of the collection returned by map()
is the same as the original collection. The lambda passed to map()
is applied on each element in the original collection, and the result is a collection of these transformed values.
A lambda passed to both filter()
and map()
takes only one parameter, but a lambda passed to reduce()
takes two parameters. The first is an accumulated value and the second is an element from the original collection. The result of the lambda is the new accumulated value. The result of reduce()
is the result of the last invocation of the lambda.
An example will help to illustrate the behavior and purpose of these three functions. For that, let’s start with a Person
class and a people
collection with some sample values.
Get hands-on with 1400+ tech skills courses.