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:



filter_none

edit
close

play_arrow

link
brightness_4
code

//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 + " ")
    }
}

chevron_right


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. filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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)
        }
    }

    chevron_right

    
    

    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. filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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)
        }
    }

    chevron_right

    
    

    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.
filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


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.
  • filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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)
        }
    }

    chevron_right

    
    

    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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
    }
}

chevron_right


Output:

Minimum: 1

Following code prints the maximum valued element:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
    }
}

chevron_right


Output:

Maximum: 6

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : shubham_singh



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.