January 2018
Intermediate to advanced
434 pages
14h 1m
English
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 filter method will look like this:
val listOfNumbers=listOf(1,2,3,4,5,6,7,8,9)var evenList=listOfNumbers.filter { it%2==0}println(evenList)//Output: [2, 4, 6, 8]
Another variant ...
Read now
Unlock full access