What are Iterators in Scala?
The use of iterators is a simple concept. They iterate or access the items from the start to the end of a collection, one item at a time.
One of the fundamental uses of iterators is dealing with large data since you do not need to load the entire data in the memory. The start index of the collection is assigned to the iterator.
This is an array list
1 of 5
In Scala, we can easily define an iterator for a collection. A collection in Scala can consist of Arrays, Lists, maps, etc. These iterator elements use the methods hasNext() and next() to access the elements.
Let’s look at coding examples to understand the use of iterators.
next(): returns the next element in the listhasNext(): checks whether there are any more remaining elements present in the list.
Code
- Here, we define iterators using collections.
object Main extends App {// define an integer arrayval arr = Array(15,3,22,13,67,89)// defining an iterator for a listval iter = arr.iterator// using hasnext and next to print elementswhile (iter.hasNext)println(iter.next)// we can also use for loop to access these elementsval iter1 = arr.iteratorprintln("Using for loop: ")for(k <- iter1) println(k)// we can also use foreach to access these elementsval iter2 = arr.iteratorprintln("Using foreach: ")iter2.foreach(println)}
- Here, we define iterators directly.
object Main extends App {// define an iteratorval iter = Iterator(15,3,22,13,67,89)// using hasnext and next to print elementswhile (iter.hasNext)println(iter.next)// we can also use for loop to access these elementsval iter1 = Iterator(15,3,22,13,67,89)println("Using for loop: ")for(k <- iter1) println(k)// we can also use foreach to access these elementsval iter2 = Iterator(15,3,22,13,67,89)println("Using foreach: ")iter2.foreach(println)}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved