问题:
你要遍历一个有序集合,同时你又想访问一个循环计数器,但最重要的是你真的不需要手动创建这个计数器。
解决方案:
使用zipWithIndex或者zip方法来自动地创建一个计数器,假设你有一个有序集合days,那么你可以使用zipWithIndex和counter来打印带有计数器的集合元素:
package localspark
/**
* @Author:wangzhen
* @Description:
* @Date:2021 /3/2
* @Project:SparkStream
* @Package:localspark
*/
object IndexTest {
def main(args: Array[String]): Unit = {
val days = Array("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday")
//TODO 等价
days.zipWithIndex.foreach{case(day,count) => println(s"$count is $day")}
for((day,count) <- days.zipWithIndex) {
println(s"$count is $day")
}
//zipWithIndex的计数器都是从0开始,如果你想指定开始的值,那么你可以使用zip Stream:
for((day,count) <- days.zip(Stream from 1)) {
println(s"$count is $day")
}
//TODO 当有序集合调用zipWithIndex的时候,它会返回一个有序的二元组集合:
val list :List[String] = List("a", "b", "c")
//返回有序而原数组
println(list.zipWithIndex)
//因为zipWithIndex是在一个已经存在的有序集合的基础上建立一个新的有序集合,你可以在调用zipWithIndex之前调用view
println(list.view.zipWithIndex)
//zip和zipWithIndex方法都返回一个有序二元组集合。因此,你的foreach方法也可以写成下面这样,虽然这比起解决方案中的方法,可读性略差。
days.zipWithIndex.foreach(d => println(s"${d._2} is ${d._1}"))
//可以通过一个for循环加range来创建这个计数器:
val fruits = Array("apple", "banana", "orange")
for (i <- 0 until fruits.size) println(s"element $i is ${fruits(i)}")
}
}