Scala中 zip或者zipWithIndex的用法

问题:
你要遍历一个有序集合,同时你又想访问一个循环计数器,但最重要的是你真的不需要手动创建这个计数器。
解决方案:
    使用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)}")
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值