- 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:
- JavaScript高效圖形編程
- Learning Selenium Testing Tools with Python
- iOS 9 Game Development Essentials
- Flask Web開發入門、進階與實戰
- Easy Web Development with WaveMaker
- 軟件架構:Python語言實現
- 深入RabbitMQ
- Spring Boot進階:原理、實戰與面試題分析
- Node.js Design Patterns
- Learning Probabilistic Graphical Models in R
- Android驅動開發權威指南
- C語言程序設計與應用(第2版)
- IBM Cognos TM1 Developer's Certification guide
- 黑莓(BlackBerry)開發從入門到精通
- Android高級開發實戰:UI、NDK與安全