Scala Collections - Iterator



An iterator is not a collection, but rather a way to access the elements of a collection one by one. The two basic operations on an iterator it are next and hasNext. A call to it.next() will return the next element of the iterator and advance the state of the iterator. You can find out whether there are more elements to return using Iterator's it.hasNext method.

The most straightforward way to "step through" all the elements returned by an iterator is to use a while loop. Let us follow the following example program.

Example

object Demo {
   def main(args: Array[String]) {
      val it = Iterator("a", "number", "of", "words")
      while (it.hasNext){
         println(it.next())
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

a
number
of
words

Find Min & Max Valued Element

You can use it.min and it.max methods to find out the minimum and maximum valued elements from an iterator. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program.

Example

object Demo {
   def main(args: Array[String]) {
      val ita = Iterator(20,40,2,50,69, 90)
      val itb = Iterator(20,40,2,50,69, 90)
      println("Maximum valued element " + ita.max )
      println("Minimum valued element " + itb.min )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Maximum valued element 90
Minimum valued element 2

Find the Length of the Iterator

You can use either it.size or it.length methods to find out the number of elements available in an iterator. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program.

Example

object Demo {
   def main(args: Array[String]) {
      val ita = Iterator(20,40,2,50,69, 90)
      val itb = Iterator(20,40,2,50,69, 90)
      println("Value of ita.size : " + ita.size )
      println("Value of itb.length : " + itb.length )
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Value of ita.size : 6
Value of itb.length : 6
Advertisements