concept filter in category kotlin

appears as: filter
Kotlin in Action

This is an excerpt from Manning's book Kotlin in Action.

Functional style provides many benefits when it comes to manipulating collections. You can use library functions for the majority of tasks and simplify your code. In this section, we’ll discuss some of the functions in the Kotlin standard library for working with collections. We’ll start with staples like filter and map and the concepts behind them. We’ll also cover other useful functions and give you tips about how not to overuse them and how to write clear and comprehensible code.

Executing this code snippet prints nothing to the console. That means the map and filter transformations are postponed and will be applied only when the result is obtained (that is, when the terminal operation is called):

The order of the operations you perform on a collection can affect performance as well. Imagine that you have a collection of people, and you want to print their names if they’re shorter than a certain limit. You need to do two things: map each person to their name, and then filter out those names that aren’t short enough. You can apply map and filter operations in any order in this case. Both approaches give the same result, but they differ in the total number of transformations that should be performed (see figure 5.9).

>>> val people = listOf(Person("Alice", 29), Person("Bob", 31), ...        Person("Charles", 31), Person("Dan", 21)) >>> println(people.asSequence().map(Person::name)    #1 ...         .filter { it.length < 4 }.toList()) [Bob, Dan] >>> println(people.asSequence().filter { it.name.length < 4 } ...         .map(Person::name).toList())            #2 [Bob, Dan] #1 - “map” goes first, then “filter”. #2 - “map” goes after “filter”.
Figure 5.9. Applying filter first helps to reduce the total number of transformations.

If map goes first, each element is transformed. If you apply filter first, inappropriate elements are filtered out as soon as possible and aren’t transformed.