How to filter and map using lambda expressions
In this recipe, we will learn how to transform a list using a map
function in Kotlin, and how to filter the list with whichever criteria we like. We will be using lambda functions, which provide a great way to do functional programming. So let's get started.
Getting ready
I'll be using IntelliJ IDEA for writing and running Kotlin code; you are free to use any IDE that can do the same task.
How to do it…
First, let's see how to use the filter function on a list. The filter function returns a list containing all elements matching the given predicate. We will create a list of numbers and filter the list based on even or odd.
The filter
method is good for an immutable collection as it doesn't modify the original collection but returns a new one. In the filter method, we need to implement the predicate. The predicate, like the condition, is based on the list that is filtered.
For example, we know that even items will follow it%2==0
. So the corresponding...