How to copy iterator in Scala?

后端 未结 4 947
星月不相逢
星月不相逢 2021-01-01 17:03

About duplicate

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

4条回答
  •  生来不讨喜
    2021-01-01 17:38

    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.

提交回复
热议问题