- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 183字
- 2021-06-10 18:49:20
Iterating over a list
Collections are used for storing and processing a set of objects. Kotlin provides an elegant syntax for iteration over a collection.
Consider the code for 9_IteratingOverList.kts:
val names = listOf("Mark", "Tina", "Williams")
for(name in names) {
println(name)
}
The output is as follows:
If we are interested in getting the index value, we can do that by running the indices command on the collection.
Consider the code for 9a_IteratingOverListIndex.kts:
val names = listOf("Mark", "Tina", "Williams")
for(index in names.indices) {
println(index)
}
The output is as follows:
As the index is a String, we can write an expression to print it. Consider the code for 9b_IteratingOverListIndex.kts:
val names = listOf("Mark", "Tina", "Joseph")
for(index in names.indices) {
println("$index")
}
The output is as follows:
We can also add names to the expression to get items out of the collection, as in the following example, in which we are printing index and name. Consider the code for 9c_IteratingOverList.kts:
val names = listOf("Mark", "Tina", "Joseph")
for(index in names.indices) {
println("$index: ${names.get(index)}")
}
The output is as follows:
- Data Visualization with D3 4.x Cookbook(Second Edition)
- Python 3.7網絡爬蟲快速入門
- Django Design Patterns and Best Practices
- oreilly精品圖書:軟件開發者路線圖叢書(共8冊)
- Python程序設計
- The Professional ScrumMaster’s Handbook
- Extreme C
- Apache Camel Developer's Cookbook
- Mastering Apache Storm
- 監控的藝術:云原生時代的監控框架
- Java EE項目應用開發
- Neo4j Graph Data Modeling
- Java與Android移動應用開發:技術、方法與實踐
- 看漫畫學Python:有趣、有料、好玩、好用(全彩版)
- Learning Spark SQL