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

前端 未结 8 1828
轮回少年
轮回少年 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-12 23:44

    Use .map in .zipWithIndex with Map data structure

    val sampleMap = Map("a" -> "hello", "b" -> "world", "c" -> "again")
    
    val result = sampleMap.zipWithIndex.map { case ((key, value), index) => 
        s"Key: $key - Value: $value with Index: $index"
    }
    

    Results

     List(
           Key: a - Value: hello with Index: 0, 
           Key: b - Value: world with Index: 1, 
           Key: c - Value: again with Index: 2
         )
    

提交回复
热议问题