Lambdas are very useful with collections and in fact, they are the backbone of the advanced manipulation of collections.
Map and Filter
The basic function to manipulate collection is filter. This function accepts as an argument a lambda and returns a new collection. The lambda is given as an argument an element of the collection and returns a Boolean. If the lambda returns TRUE for an element, that element is added to the new collection, otherwise, it is excluded.
1 2 3 |
val li = listOf(1, 2, 3, 4) // it prints [2,4] println(li.filter( i: Int -> i % 2 == 0 })) |
In this example, the filter function returns all even numbers.
The function map creates a new collection created by applying the lambda supplied to map to each element of the collection.
1 2 3 |
val li = listOf(1, 2, 3, 4) // we use the it implicit parameter println(li.map { it * 2 }) // it prints [2, 4, 6, 8] |
find and groupBy
The function find returns the first element of the collection that satisfies the condition set in the lambda. It is the same function as firstOrNull, which is a longer but also clearer name,
which is a longer but also clearer name.
1 2 3 4 5 6 |
val list = listOf(1, 2, 3, 4) println(list.find({ it % 2 == 0 })) // it prints 2 val set = setOf("book", "very", "short") println(set.find {it.length < 4}) // it prints "null" println(set.find {it.length > 4}) // it prints "short" |
The function groupBy allows dividing a collection into more groups according to the condition indicated.
1 2 3 4 5 6 7 8 9 10 11 12 |
data class Number(val name: String, val value: Int) val list = listOf(Number("one", 3), Number("two", 3), Number("three", 5)) // it prints // {3=[Number(name=one, value=3), Number(name=two, value=3)], // 5=[Number(name=three, value=5)]} println(list.groupBy { it.value }) val set = setOf(1, 2, 3, 4) // it prints // {false=[1, 3], true=[2, 4]} println(set.groupBy({ it % 2 == 0 })) |
fold
The method fold collapses a collection to a unique value, using the provided lambda and a starting value.
1 2 3 4 5 |
val list = listOf(5, 10) // it prints 15 println(list.fold(0, { start, element -> start + element })) // it prints 0 println(list.fold(15, { start, element -> start - element })) |
In the previous example, the first time we start with 0 and added all elements until the end. In the second case, with start with 15 and subtracted alle elements. Basically, the provided value is used as an argument for the start in the first cycle, then the start becomes the value returned by the previous cycle.
So, in the first case the function behaves like this:
- start = 0, element = 5 -> result 5
- start = 5, element = 10 -> result 15
For more details, you can take alook on the following links:-
https://kotlinlang.org/docs/reference/collection-filtering.html
https://kotlinlang.org/docs/reference/collection-grouping.html