0

I have a mutable.LinkedHashMap and try to remove item in a for-loop. However, if remove occurs, the for-loop also stops.

scala> val a = mutable.LinkedHashMap[Int, Int](1->1, 2->2, 3->3)
# when no remove occurs, for-loop works as expected
scala> for( (k,v) <- a ) { println(k);  }
1
2
3
# following code doesn't work, only remove 1 and stop
scala> for( (k,v) <- a ) { println(k); a.remove(k) }
1
# following code work as expected
scala> a.keys.foreach{ k => println(k); a.remove(k) }
1
2
3

I am curious why remove stop for-loop.

xiangl
  • 13
  • 2
  • 2
    Updating the collection while iterating, invalidates the iterator. In last case you are iterating on collection returned by `a.keys` so that works as expected. – Ashwani Sep 02 '19 at 18:19

1 Answers1

1

"remove on iteration" works fine in "2.13.0-M5" but not on earlier versions. But still not recommended cut a tree branch you are on.

See 2.13 example: https://scastie.scala-lang.org/prayagupd/Cq2wUKP3TtmaL5IDMVKRfw/7

import scala.collection.mutable

val data = mutable.LinkedHashMap[Int, Int](1 -> 1, 2 -> 2, 3 -> 3)

println("before: " + data)

for ((k, v) <- data) {
  println("removing key: " + k + " from map " + data)
  data.remove(k)
}

println("after: " + data)

output:

before: LinkedHashMap(1 -> 1, 2 -> 2, 3 -> 3)
removing key: 1 from map LinkedHashMap(1 -> 1, 2 -> 2, 3 -> 3)
removing key: 2 from map LinkedHashMap(2 -> 2, 3 -> 3)
removing key: 3 from map LinkedHashMap(3 -> 3)
after: LinkedHashMap()
prayagupa
  • 30,204
  • 14
  • 155
  • 192