Scala Iterator toBuffer() method with example

The toBuffer() method belongs to the concrete value members of the Class AbstractIterator. It is defined in the classes TraversableOnce and GenTraversableOnce. It employs the contents of the stated traversable or iterator to produce a new mutable buffer. It won’t end for infinite-sized collections.

Method Definition: def toBuffer: Buffer[B]

Return Type: It returns a buffer from the stated iterator’s elements.



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of toBuffer()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Declaring an iterator
        val iter = Iterator(3, 2, 5, 9)
          
        // Applying toBuffer method
        val result = iter.toBuffer
              
        // Displays output
        println(result)
  
    }
}

chevron_right


Output:

ArrayBuffer(3, 2, 5, 9)

Here, an Array Buffer is returned from the Iterator elements.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of toBuffer()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Declaring an empty-iterator
        val iter = Iterator()
          
        // Applying toBuffer method
        val result = iter.toBuffer
              
        // Displays output
        println(result)
  
    }
}

chevron_right


Output:

ArrayBuffer()

Here, an empty-Array Buffer is returned from an empty Iterator.



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.