Open In App

Iterators in Scala

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.



  2. // 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
    
  3. 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.



  4. // 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
    
  5. 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

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.


    Article Tags :