Skip to content
Related Articles

Related Articles

Iterators in Scala
  • Last Updated : 30 Sep, 2019
GeeksforGeeks - Summer Carnival Banner

An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Therefore, iterators are useful when the data is too large for the memory. To access elements we can make use of hasNext() to check if there are elements available and next() to print the next element.
Syntax:

val v = Iterator(5, 1, 2, 3, 6, 4)

//checking for availability of next element
while(v.hasNext)

//printing the element
println(v.next)

 
Defining an iterator for a collection

We can define an iterator for any collection(Arrays, Lists, etc) and can step through the elements of that particular collection.
Example:




//Scala iterator program
//for defining iterator
  
//Creating object
object GFG
{
    // Main method
    def main(args:Array[String])
    {
        val v = Array(5,1,2,3,6,4)
        //val v = List(5,1,2,3,6,4)
      
        // defining an iterator
        // for a collection
        val i = v.iterator
      
        while (i.hasNext)
            print(i.next + " ")
    }
}

Output:

5 1 2 3 6 4 

 
Ways to access elements



  1. Using while loop: Simplest way to access elements is to use while loop along with hasNext and next methods.




    // Scala iterator program
    // for accessing using while
      
    // Creating object
    object GFG
    {
        // Main method
        def main(args:Array[String])
        {
            // defining iterator
            val i = Iterator(5, 1, 2, 3, 6, 4)
          
            /*
            OR
            val v = List(5, 1, 2, 3, 6, 4)
            val i = v.iterator
            */
          
            // accessing elements using while loop
            while (i.hasNext)
                println(i.next)
        }
    }

    Output:

    5
    1
    2
    3
    6
    4
    
  2. Using foreach action: We can make use of foreach to print elements by passing println function as parameter. Note that foreach is a higher order function that takes another function as parameter. In other words, println function is applied on every element.




    // Scala iterator program
    // for accessing using foreach
      
    // Creating object
    object GFG
    {
        // Main method
        def main(args:Array[String])
        {
            // defining iterator
            val i = Iterator(5, 1, 2, 3, 6, 4)
          
            /*
            OR
            val v = List(5, 1, 2, 3, 6, 4)
            val i = v.iterator
            */
          
            // accessing elements using foreach
            i foreach println
            // same as i.foreach(println)
        }
    }

    Output:

    5
    1
    2
    3
    6
    4
    
  3. Using for loop: Another straightforward way is to use for loop. It works in very similar way as accessing elements of any collection using for loop.




// Scala iterator program
// for accessing using for
  
// Creating object
object GFG
{
    // Main method
    def main(args:Array[String])
    {
        // defining iterator
        val i = Iterator(5, 1, 2, 3, 6, 4)
      
        /*
        OR
        val v = List(5, 1, 2, 3, 6, 4)
        val i = v.iterator
        */
      
        // accessing elements using for loop
        for(k <- i) println(k)
    }
}

Output:

5
1
2
3
6
4

 
Finding elements with minimum and maximum values

  • Using built-in functions min and max Iterators can be traversed only once. Therefore, we should redefine the iterator after finding the maximum value.




    // Scala iterator program for minimum
    // and maximum valued element
    // using built-in methods
      
    // Creating object
    object GFG
    {
        // Main method
        def main(args:Array[String])
        {
            // defining iterator
            val i1 = Iterator(5, 1, 2, 3, 6, 4)
          
            // calling max function
            println("Maximum: "+ i1.max)
          
            // redefining iterator
            val i2 = Iterator(5, 1, 2, 3, 6, 4)
          
            // calling min function
            println("Minimum: "+ i2.min)
        }
    }

    Output:

    Maximum: 6
    Minimum: 1
  • User-defined functions to return minimum and maximum value. we can define our own pure functions as per our convenience to print minimum and maximum valued element.

Following code prints the minimum valued element:




// Scala iterator program
// for minimum valued element
// user defined method
  
// Creating object
object GFG
{
    // parameter is an Iterator of Int
    // returning Int value
    def small(ite : Iterator[Int]) : Int = 
    {
          
        // storing first value of collection
        var mn = ite.next
  
        for(i <- ite)
        if(i < mn) mn = i
          
        // returning     
        mn
          
    }
      
    // Main method
    def main(args:Array[String])
    {
        // defining iterator
        val i = Iterator(5, 1, 2, 3, 6, 4)
      
        //calling small function
        println("Minimum: "+ small(i))
    }
}

Output:

Minimum: 1

Following code prints the maximum valued element:




// Scala iterator program
// for maximum valued element
// user defined method
  
// Creating object
object GFG
{
    // parameter is an Iterator of Int
    // returning Int value
    def large(ite: Iterator[Int]): Int =
    {
          
        // storing first value of collection
        var mx = ite.next
  
        for(i <- ite)
        if(i > mx) mx = i
          
        // returning
        mx
    }
      
    // Main method
    def main(args:Array[String])
    {
        // defining iterator
        val i = Iterator(5, 1, 2, 3, 6, 4)
      
        // calling large function
        println("Maximum: "+ large(i))
    }
}

Output:

Maximum: 6

NOTE: Both functions large() and small() are written as two separate codes to reduce burden on online compiler.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :