官术网_书友最值得收藏!

Getting ready

Let's consider the following example:

val collection = listOf("a", "b", "c", "d", "e", "f", "g", "h")
val transformedCollection = collection.map {
println("Applying map function for $it")
it
}
println(transformedCollection.take(2))

In the first line, we created a list of strings and assigned it to the collection variable. Next, we are applying the map() function to the list. Mapping operation allows us to transform each element of the collection and return a new value instead of the original one. In our case, we are using it just to observe that map() was invoked by printing the message to the console. Finally, we want to filter our collection to contain only the first two elements using the take() function and print the content of the list to the console.

In the end, the preceding code prints the following output:

Applying map function for a
Applying map function for b
Applying map function for c
Applying map function for d
Applying map function for e
Applying map function for f
Applying map function for g
Applying map function for h
[a, b]

As you can see, the map() function was properly applied to every element of the collection and the take() function has properly filtered the elements of the list. However, it would not be an optimal implementation if we were working with a larger dataset. Preferably, we would like to wait with the execution of the data-processing operations until we know what specific elements of the dataset we really need, and then apply those operations only to those elements. It turns out that we can easily optimize our scenario using the Sequence data structure. Let's explore how to do it in the next section.

主站蜘蛛池模板: 山东省| 积石山| 富民县| 滦平县| 启东市| 合川市| 侯马市| 高密市| 府谷县| 鹤岗市| 兴国县| 河池市| 阿城市| 万山特区| 齐齐哈尔市| 五华县| 靖州| 英山县| 长岛县| 姚安县| 沙湾县| 丘北县| 金乡县| 西平县| 砀山县| 乳源| 宜丰县| 台山市| 镇赉县| 敖汉旗| 罗甸县| 武平县| 合作市| 太仓市| 洪雅县| 循化| 娱乐| 泸定县| 蛟河市| 广东省| 兴安盟|