- 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:
- Instant Node Package Manager
- C++案例趣學(xué)
- 算法基礎(chǔ):打開(kāi)程序設(shè)計(jì)之門(mén)
- Designing Hyper-V Solutions
- Oracle BAM 11gR1 Handbook
- Nginx Essentials
- Web程序設(shè)計(jì)(第二版)
- Learning Data Mining with R
- C語(yǔ)言程序設(shè)計(jì)同步訓(xùn)練與上機(jī)指導(dǎo)(第三版)
- Java程序設(shè)計(jì)
- JavaCAPS基礎(chǔ)、應(yīng)用與案例
- Java Web開(kāi)發(fā)詳解
- 汽車人機(jī)交互界面整合設(shè)計(jì)
- Emotional Intelligence for IT Professionals
- 分布式數(shù)據(jù)庫(kù)原理、架構(gòu)與實(shí)踐