Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are Iterators in Scala?

Sarvech Qadir

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 list
  • hasNext(): checks whether there are any more remaining elements present in the list.

Code

  1. Here, we define iterators using collections.
object Main extends App {
    // define an integer array
    val arr = Array(15,3,22,13,67,89)

    // defining an iterator for a list
    val iter = arr.iterator
    // using hasnext and next to print elements
    while (iter.hasNext)
        println(iter.next)

    // we can also use for loop to access these elements
    val iter1 = arr.iterator
    println("Using for loop: ")
    for(k <- iter1) println(k)

    // we can also use foreach to access these elements
    val iter2 = arr.iterator
        println("Using foreach: ")
    iter2.foreach(println)
}
  1. Here, we define iterators directly.
object Main extends App {
    // define an iterator
    val iter = Iterator(15,3,22,13,67,89)
    
    // using hasnext and next to print elements
    while (iter.hasNext)
        println(iter.next)

    // we can also use for loop to access these elements
    val 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 elements
    val iter2 = Iterator(15,3,22,13,67,89)
        println("Using foreach: ")
    iter2.foreach(println)
}

RELATED TAGS

scala

CONTRIBUTOR

Sarvech Qadir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring