Scala Iterator concatenation with example

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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())
      
        }
    }
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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())
      
        }
    }
}

chevron_right


Output:

0
1



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.