I am trying to do a for loop on a HashMap in Scala, but I also need a count of my iteration, like an index of sorts. Here is what I want the functionality to be:
val map = HashMap()
val i = 0;
for ((k, v) <- map) {
// do something
i += 1
}
But I want it to look something like this, where i is updated inside the for loop syntax. But, this seems to act as a nested loop rather than a parallel iterator.
for ((k, v) <- map; i <- 0 until map.size) {
// do something
}
for (((k, v), i) <- map.zipWithIndex) {map,flatMap, andforeachmethods on most collections so that you don't need to write the boilerplate of a for loop. It's much easier to writecollection.foreach(println)than a for loop that does that same thing.map,flatMap, andfilter.