How can I use map and receive an index as well in Scala?

前端 未结 8 1826
轮回少年
轮回少年 2020-12-12 23:07

Is there any List/Sequence built-in that behaves like map and provides the element\'s index as well?

8条回答
  •  醉酒成梦
    2020-12-13 00:05

    There are two ways of doing this.

    ZipWithIndex: Creates a counter automatically starting with 0.

      // zipWithIndex with a map.
      val days = List("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
      days.zipWithIndex.map {
            case (day, count) => println(s"$count is $day")
      }
      // Or use it simply with a for.
      for ((day, count) <- days.zipWithIndex) {
            println(s"$count is $day")
      }
    

    Output of both code will be:

    0 is Sun
    1 is Mon
    2 is Tue
    3 is Wed
    4 is Thu
    5 is Fri
    6 is Sat
    

    Zip: Use zip method with a Stream to create a counter. This gives you a way to control the starting value.

    for ((day, count) <- days.zip(Stream from 1)) {
      println(s"$count is $day")
    }
    

    Result:

    1 is Sun
    2 is Mon
    3 is Tue
    4 is Wed
    5 is Thu
    6 is Fri
    7 is Sat
    

提交回复
热议问题