Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use iterators in Scala

Sheza Munir

Iterators allow the user to access elements in a collection one by one. They are very beneficial when the data being processed is large and cannot be accessed all at once.

We usually use the keyword it to refer to an iterator.


Common methods associated with iterators are next and hasNext. it.hasNext checks if there is an element after the current one in the collection. returns the next element.


There are two ways to declare an iterator:

  1. Direct: While declaring the collection, put it in parentheses with the iterator keyword.
val it = Iterator(1, 2, 3, 4, 5)
  1. Indirect: The collection is declared first, and then connected with the iterator.
val v = List(1, 2, 3, 4, 5)
val it = v.iterator

Usage with loops

We commonly use iterators with loops to step through the collection. The most common loop with iterators is the while loop, which runs until there is a next element (condition checks for it.hasNext).


The following code shows the implementation of iterators in Scala:

object Main extends App{
  // direct declaration of iterator
  val it_1 = Iterator(1, 2, 3, 4, 5)

  //iterating through the collection
      println (

  //indirect declaration of iterator
  val v = List(6, 7, 8, 9, 10)
  val it_2 = v.iterator

  //iterating through the collection
      println (

  // using for loop with iterator 
  val it_3 = Iterator(11, 12, 13, 14, 15)
  for(k <- it_3) println(k)




Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring