- Kotlin Standard Library Cookbook
- Samuel Urbanowicz
- 292字
- 2021-07-23 19:05:50
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.
- Learning Neo4j
- FuelPHP Application Development Blueprints
- Microsoft Application Virtualization Cookbook
- 自己動手實現(xiàn)Lua:虛擬機、編譯器和標準庫
- OpenNI Cookbook
- Visual Basic學習手冊
- EPLAN實戰(zhàn)設計
- Python數(shù)據(jù)分析從0到1
- Linux C編程:一站式學習
- 一塊面包板玩轉(zhuǎn)Arduino編程
- Machine Learning in Java
- 持續(xù)集成與持續(xù)交付實戰(zhàn):用Jenkins、Travis CI和CircleCI構(gòu)建和發(fā)布大規(guī)模高質(zhì)量軟件
- Android Development Tools for Eclipse
- Google Adsense優(yōu)化實戰(zhàn)
- Arduino Electronics Blueprints