Is there any List/Sequence built-in that behaves like map and provides the element\'s index as well?
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