0

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
    }
4
  • 5
    You can for (((k, v), i) <- map.zipWithIndex) { Commented Feb 26, 2020 at 22:03
  • I think it's worth making this an answer. ;) Commented Feb 27, 2020 at 5:53
  • I would avoid for loops in Scala. They're not very functional, and Scala provides map, flatMap, and foreach methods on most collections so that you don't need to write the boilerplate of a for loop. It's much easier to write collection.foreach(println) than a for loop that does that same thing. Commented Feb 27, 2020 at 17:16
  • @csjacobs24Scala doesn't have for loops! Although for comprehensions look similar on the surface, it all desugars into map, flatMap, and filter. Commented Feb 27, 2020 at 20:04

1 Answer 1

4

The zipWithIndex method is designed specifically for this purpose:

for {((k, v), i) <- map.zipWithIndex} yield {???}

or

map.zipWithIndex.collect { case ((k, v), i) => ??? }

Personally I would use the second version in this case and only use the for syntax when iterating over multiple collections.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.