Kotlin 中的循环和遍历常用写法


Kotlin学习总结


循环的5中写法

  • 只有until的写法是左闭右开的,不包含最后一个值
fun main() {
     
    //1,2,3,4,5,6,7,8,9,10,
    for (i in 1..10) {
     
        myprint(i)
    }
    println()
    //1,2,3,4,5,6,7,8,9,
    for (i in 1 until 10) {
     
        myprint(i)
    }
    println()
    //10,9,8,7,6,5,4,3,2,1,
    for (i in 10 downTo 1) {
     
        myprint(i)
    }
    println()
    //1,3,5,7,9,
    for (i in 1..10 step 2) {
     
        myprint(i)
    }
    println()
    //0,1,2,3,4,5,6,7,8,9,
    repeat(10) {
     
        myprint(it)
    }
    println()
}

fun myprint(i: Int) {
     
    print("$i,")
}

集合的遍历

fun main() {
     
    //list
    val index = arrayOf(1, 2, 3, 4, 5, 6)
    index.forEach {
     
        print(it)
    }
    println()
    for (it in index) {
     
        print(it)
    }
    println()
    //map
    var map = mapOf("k1" to 1, "k2" to 2)
    for ((k, v) in map) {
     
        println("$k , $v , ${
       map[k]}")
    }
    map.forEach{
     
        println("${
       it.key} , ${
       it.value}")
    }
}
//123456
//123456
//k1 , 1 , 1
//k2 , 2 , 2
//k1 , 1
//k2 , 2

你可能感兴趣的:(kotlin)