Open In App

Scala Iterator concatenation with example

Last Updated : 30 Jun, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The concatenation of the Scala iterators is done by utilizing the operator ++. It belongs to the concrete value members of the class AbstractIterator. It is utilized to add the elements of the two iterators.
It is defined in the class Iterator.

Method Definition : def ++(that: => Iterator[A]): Iterator[A]

Return Type : It returns the concatenation of two iterators.

Example #1:




// Scala program of concatenation
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Applying ++ operator
        val result = Iterator(2,4).++(Iterator(6,7))
          
        // Applying while loop
        while(result.hasNext)
        {
          
        // Displays output
        println(result.next())
      
        }
    }
}


Output:

2
4
6
7

Therefore, both the iterator’s elements are added and here we have utilized hasNext and next methods, which can be called on an Iterator in Scala.
Example #2:




// Scala program of concatenation
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Applying ++ operator
        val result = Iterator(0).++(Iterator(1))
          
        // Applying while loop
        while(result.hasNext)
        {
          
        // Displays output
        println(result.next())
      
        }
    }
}


Output:

0
1


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads