Search code examples
scalaiteratorcomparison

How to compare two iterators in scala?


For now, I have only 3 way to compare two iterators (with String type) in scala:

// 1.
it1 sameElements it2

// 2.
it2.toList == it2.toList

// 3. 
def compare(it1:Iterator[String], it2:Iterator[String]) {
  while (it1.hasNext) {
    if (!it2.hasNext) return false
    if (it1.next != it2.next) {
      return false
    }
  }
  return !it2.hasNext
}

Is there any other good ways to do this?


Solution

  • I would use zip:

    def compare(it1:Iterator[String], it2:Iterator[String]) = {
      it1.zip(it2).forall(x => x._1 == x._2) && 
      (it1.length == it2.length)    
    }
    

    Or you can also use tail recursion:

    def compare(it1:Iterator[String], it2:Iterator[String]) : Boolean = {
      (it1 hasNext, it2 hasNext) match{
        case (true, true) => (it1.next == it2.next) && compare(it1, it2)
        case (false, false) => true
        case _ => false
      }
    }
    

    The function used for sameElements, which I recommend as it is used in the API, I modified the source signature for readability

    def compare(it1:Iterator[String], it2:Iterator[String]) = {
      while (it1.hasNext && it2.hasNext)
        if (it1.next != it2.next) return false
      !it1.hasNext && !it2.hasNext
    }