在Kotlin中,使用for循环遍历集合时,可以很方便地同时获取每个元素的索引和值。以下是一些方法和示例代码,展示了如何在Kotlin的for循环中获取索引和值。 1. 使用withIndex()函数 withIndex()是Kotlin标准库中的一个扩展函数,它可以为集合中的每个元素生成一个索引和值的对(Pair)。在for循环中,可以解构这个对来分别...
for ((index, value) in intArray.withIndex()) { Log.e(TAG, "for语句:withIndex == index: $index, value: $value") } 1. 2. 3. 4. 5. 打印数据如下: for语句:withIndex == index: 0, value: 10 for语句:withIndex == index: 1, value: 20 for语句:withIndex == index: 2, value:...
val numbers = listOf(1, 2, 3, 4, 5) numbers.forEach { number -> println(number * 2) } 6. 使用withIndex 如果你需要同时访问元素的索引和值,可以使用withIndex。 代码语言:txt 复制 val fruits = listOf("apple", "banana", "cherry") for ((index, fruit) in fruits.withIndex()) { pri...
let,with,run,apply,also函数区别 https://blog.csdn.net/u013064109/article/details/78786646 //kotlin 的集中for,不包含迭代器的方式val al =listOf("ab","ab","ab","ab","ab","ab")//对象方式for( value in al){ }//下标for( index in 5..6){ }//倒叙for( index in 6 downTo 1){ }...
for (i in arrays.indices) { println(arrays[i]) } } 1. 2. 3. 4. 5. 6. 注意这种”在区间上遍历”会编译成优化的实现而不会创建额外对象。 或者你可以用库函数withIndex: fun main(args: Array<String>) { val arrays = arrayOf(1,2,3,4,5) ...
通过forEach遍历数组 通过区间表达式遍历数组(..、downTo、until) 通过indices遍历数组 通过withIndex遍历数组 通过forEach遍历数组 先来看看通过forEach遍历数组,和其他的遍历数组的方式,有什么不同。 array.forEach { value -> } 反编译后: Integer[] var5 = array; ...
for ( i in array.indices )println ( array [i] )等同于 下面的 i in args A:for (arg in args) { //for ( i in array.indices) {...} println(arg)}B:库函数 withIndexfor ((index, value) in args.withIndex()) {println("$index->$value")...
for (index in array.indices) { } 反编译后: for(int var4 = array.length; var3 < var4; ++var3) { } 通过indices 遍历数组, 编译之后的代码 ,除了创建了一些临时变量,并没有创建额外的对象。 通过withIndex 遍历数组 withIndex 和indices 遍历数组的方式相似,通过 withIndex 遍历数组,不仅可以获取的...
for (index in 0 until length) { val element = get(index) // 调用作为参数传递给"predicate"函数 if (predicate(element)) sb.append(element) } return sb.toString() } // 传递一个lambda,作为predicate参数 println("ab3d".filter { c -> c in 'a'..'z' }) ...
for (item in collection.size - 1 downTo 0) { //迭代操作 } ``` 上述代码将会从集合的最后一个元素开始迭代到第一个元素。 5.带有索引的for循环 如果我们既需要访问元素,又需要访问索引,可以使用withIndex()方法。它会返回一个带有索引的迭代器。例如: ```kotlin for ((index, item) in collection.wi...