Scala Iterator toList() method with example

The toList() method belongs to the concrete value members of the AbstractIterable class and is defined in the TraversableOnce and GenTraversableOnce classes. It converts a traversable or iterator to a list but it doesn’t terminates for infinite-sized collections.

  • Method Definition:

    def toList: List[A]
    
  • Return Type:
    It returns a list from the stated traversable or an iterator.>/li>

Example :



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

List(8, 9, 10, 11)

Therefore, a List is generated from an iterator.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

List()

Therefore, an empty List is generated 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.