方法

直接倒序for循环,并删除

var mutableListOf = mutableListOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")
    println(mutableListOf)
    for (index in mutableListOf.count() - 1 downTo 0) {
        if (index > 5) {
            mutableListOf.removeAt(index)
        }
    }
    println(mutableListOf)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[0, 1, 2, 3, 4, 5]

HashMap 的遍历

val hashMapOf = hashMapOf(
            "a" to "a",
            "b" to "b",
            "c" to "c",
            "d" to "d",
            "e" to "e"
    )
    val iterator = hashMapOf.entries.iterator()
    while (iterator.hasNext()){
        val next = iterator.next()
        println(next.key)
        iterator.remove()
    }