Scala Iterators

Advertisements


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 see a real example:

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

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
a
number
of
words

C:/>

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. Following is the usage:

object Test {
   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 )

   }
}

Here, we used ita and itb to perform two different operations because iterator can be traversed only once. When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
Maximum valued element 90
Minimum valued element 2

C:/>

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. Following is the usage:

object Test {
   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 )

   }
}

Here, we used ita and itb to perform two different operations because iterator can be traversed only once. When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
Value of ita.size : 6
Value of itb.length : 6

C:/>

Scala Iterator Methods:

Following are the important methods which you can use while playing with Iterator. For a complete list of methods available, please check official documentation of Scala.

SNMethods with Description
1def hasNext: Boolean
Tests whether this iterator can provide another element.
2def next(): A
Produces the next element of this iterator.
3def ++(that: => Iterator[A]): Iterator[A]
Concatenates this iterator with another.
4def ++[B >: A](that :=> GenTraversableOnce[B]): Iterator[B]
Concatenates this iterator with another.
5def addString(b: StringBuilder): StringBuilder
Returns the string builder b to which elements were appended.
6def addString(b: StringBuilder, sep: String): StringBuilder
Returns the string builder b to which elements were appended using a separator string.
7def buffered: BufferedIterator[A]
Creates a buffered iterator from this iterator.
8def contains(elem: Any): Boolean
Tests whether this iterator contains a given value as an element.
9def copyToArray(xs: Array[A], start: Int, len: Int): Unit
Copies selected values produced by this iterator to an array.
10def count(p: (A) => Boolean): Int
Counts the number of elements in the traversable or iterator which satisfy a predicate.
11def drop(n: Int): Iterator[A]
Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.
12def dropWhile(p: (A) => Boolean): Iterator[A]
Skips longest sequence of elements of this iterator which satisfy given predicate p, and returns an iterator of the remaining elements.
13def duplicate: (Iterator[A], Iterator[A])
Creates two new iterators that both iterate over the same elements as this iterator (in the same order).
14def exists(p: (A) => Boolean): Boolean
Returns true if the given predicate p holds for some of the values produced by this iterator, otherwise false.
15def filter(p: (A) => Boolean): Iterator[A]
Returns an iterator over all the elements of this iterator that satisfy the predicate p. The order of the elements is preserved.
16def filterNot(p: (A) => Boolean): Iterator[A]
Creates an iterator over all the elements of this iterator which do not satisfy a predicate p.
17def find(p: (A) => Boolean): Option[A]
Finds the first value produced by the iterator satisfying a predicate, if any.
18def flatMap[B](f: (A) => GenTraversableOnce[B]): Iterator[B]
Creates a new iterator by applying a function to all values produced by this iterator and concatenating the results.
19def forall(p: (A) => Boolean): Boolean
Returns true if the given predicate p holds for all values produced by this iterator, otherwise false.
20def foreach(f: (A) => Unit): Unit
Applies a function f to all values produced by this iterator.
21def hasDefiniteSize: Boolean
Returns true for empty Iterators, false otherwise.
22def indexOf(elem: B): Int
Returns the index of the first occurrence of the specified object in this iterable object.
23def indexWhere(p: (A) => Boolean): Int
Returns the index of the first produced value satisfying a predicate, or -1.
24def isEmpty: Boolean
Returns true if hasNext is false, false otherwise.
25def isTraversableAgain: Boolean
Tests whether this Iterator can be repeatedly traversed.
26def length: Int
Returns the number of elements in this iterator. The iterator is at its end after this method returns.
27def map[B](f: (A) => B): Iterator[B]
Returns a new iterator which transforms every value produced by this iterator by applying the function f to it.
28def max: A
Finds the largest element. The iterator is at its end after this method returns.
29def min: A
Finds the minumum element. The iterator is at its end after this method returns.
30def mkString: String
Displays all elements of this traversable or iterator in a string.
31def mkString(sep: String): String
Displays all elements of this traversable or iterator in a string using a separator string.
32def nonEmpty: Boolean
Tests whether the traversable or iterator is not empty.
33def padTo(len: Int, elem: A): Iterator[A]
Appends an element value to this iterator until a given target length is reached.
34def patch(from: Int, patchElems: Iterator[B], replaced: Int): Iterator[B]
Returns this iterator with patched values.
35def product: A
Multiplies up the elements of this collection.
36def sameElements(that: Iterator[_]): Boolean
Returns true, if both iterators produce the same elements in the same order, false otherwise.
37def seq: Iterator[A]
Returns a sequential view of the collection.
38def size: Int
Returns the number of elements in this traversable or iterator.
39def slice(from: Int, until: Int): Iterator[A]
Creates an iterator returning an interval of the values produced by this iterator.
40def sum: A
Returns the sum of all elements of this traversable or iterator with respect to the + operator in num.
41def take(n: Int): Iterator[A]
Returns an iterator producing only of the first n values of this iterator, or else the whole iterator, if it produces fewer than n values.
42def toArray: Array[A]
Returns an array containing all elements of this traversable or iterator.
43def toBuffer: Buffer[B]
Returns a buffer containing all elements of this traversable or iterator.
44def toIterable: Iterable[A]
Returns an Iterable containing all elements of this traversable or iterator. This will not terminate for infinite iterators.
45def toIterator: Iterator[A]
Returns an Iterator containing all elements of this traversable or iterator. This will not terminate for infinite iterators.
46def toList: List[A]
Returns a list containing all elements of this traversable or iterator.
47def toMap[T, U]: Map[T, U]
Returns a map containing all elements of this traversable or iterator.
48def toSeq: Seq[A]
Returns a sequence containing all elements of this traversable or iterator.
49def toString(): String
Converts this iterator to a string.
50def zip[B](that: Iterator[B]): Iterator[(A, B)
Returns a new iterator containing pairs consisting of corresponding elements of this iterator and that. The number of elements returned by the new iterator is the minimum of the number of elements returned by this iterator and that.


Advertisements
Advertisements