Kotlin笔记-ForEach与ForEachIndexed区别

ForEach与ForEachIndexed 区别

fun main(args: Array < String > ) {
val strArray = arrayOf(“张飞”,“关于”,“刘备”)
// 遍历集合
strArray.forEach { item ->
println(item)
}//可以使用Lambda表达式
val set = setOf(“1”,“2”,“3”,“4”)
set.forEachIndexed { index, value ->
println("$ index,$ value")
}//可以返回索引值
}

从上述代码中可以看出ForEach遍历数组是比较方便的,集合Lambda表达式能更快的遍历数组,但是如果我们要从ForEach中查找元素中的索引是比较困难的一件的事情.就这样Kotlin为我们提供了一个快速遍历并且可以打印出元素索引的方法

ForEachIndexed 遍历数组中的元素并且打印出index索引值,具体用法可看上述我提供的代码,非常的简单

猜你喜欢

转载自blog.csdn.net/weixin_44761758/article/details/89432004