How to copy iterator in Scala?
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
.
You can't duplicate an iterator without destroying it. The contract for iterator
is that it can only be traversed once.
The question you linked to shows how to get two copies in exchange for the one you've destroyed. You cannot keep using the original, but you can now run the two new copies forward independently.
As Rex said, it is impossible to make a copy of an Iterator without destroying it. That said, what is the problem with duplicate
?
var list = List(1,2,3,4,5)
var it1 = list.iterator
it1.next()
val (it1a, it1b) = it1.duplicate
it1 = it1a
var it2 = it1b
it2.next()
println(it1.next())