This is NOT a duplicate of How to clone an iterator?
Please do not blindly close this question, all the answers given in so-called
It's pretty easy to create a List
iterator that you can duplicate without destroying it: this is basically the definition of the iterator
method copied from the List
source with a fork
method added:
class ForkableIterator[A] (list: List[A]) extends Iterator[A] {
var these = list
def hasNext: Boolean = !these.isEmpty
def next: A =
if (hasNext) {
val result = these.head; these = these.tail; result
} else Iterator.empty.next
def fork = new ForkableIterator(these)
}
Use:
scala> val it = new ForkableIterator(List(1,2,3,4,5,6))
it: ForkableIterator[Int] = non-empty iterator
scala> it.next
res72: Int = 1
scala> val it2 = it.fork
it2: ForkableIterator[Int] = non-empty iterator
scala> it2.next
res73: Int = 2
scala> it2.next
res74: Int = 3
scala> it.next
res75: Int = 2
I had a look at doing this for HashMap
but it seems more complicated (partly because there are different map implementations depending on collection size). So probably best to use the above implementation on yourMap.toList
.