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. it.next returns the next element.
There are two ways to declare an iterator:
iterator keyword.val it = Iterator(1, 2, 3, 4, 5)
val v = List(1, 2, 3, 4, 5)
val it = v.iterator
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 iteratorval it_1 = Iterator(1, 2, 3, 4, 5)//iterating through the collectionwhile(it_1.hasNext){println (it_1.next)}//indirect declaration of iteratorval v = List(6, 7, 8, 9, 10)val it_2 = v.iterator//iterating through the collectionwhile(it_2.hasNext){println (it_2.next)}// using for loop with iteratorval it_3 = Iterator(11, 12, 13, 14, 15)for(k <- it_3) println(k)}
Free Resources