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.

SN Methods with Description
1

def hasNext: Boolean

Tests whether this iterator can provide another element.

2

def next(): A

Produces the next element of this iterator.

3

def ++(that: => Iterator[A]): Iterator[A]

Concatenates this iterator with another.

4

def ++[B >: A](that :=> GenTraversableOnce[B]): Iterator[B]

Concatenates this iterator with another.

5

def addString(b: StringBuilder): StringBuilder

Returns the string builder b to which elements were appended.

6

def addString(b: StringBuilder, sep: String): StringBuilder

Returns the string builder b to which elements were appended using a separator string.

7

def buffered: BufferedIterator[A]

Creates a buffered iterator from this iterator.

8

def contains(elem: Any): Boolean

Tests whether this iterator contains a given value as an element.

9

def copyToArray(xs: Array[A], start: Int, len: Int): Unit

Copies selected values produced by this iterator to an array.

10

def count(p: (A) => Boolean): Int

Counts the number of elements in the traversable or iterator which satisfy a predicate.

11

def drop(n: Int): Iterator[A]

Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.

12

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

13

def duplicate: (Iterator[A], Iterator[A])

Creates two new iterators that both iterate over the same elements as this iterator (in the same order).

14

def exists(p: (A) => Boolean): Boolean

Returns true if the given predicate p holds for some of the values produced by this iterator, otherwise false.

15

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

16

def filterNot(p: (A) => Boolean): Iterator[A]

Creates an iterator over all the elements of this iterator which do not satisfy a predicate p.

17

def find(p: (A) => Boolean): Option[A]

Finds the first value produced by the iterator satisfying a predicate, if any.

18

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

19

def forall(p: (A) => Boolean): Boolean

Returns true if the given predicate p holds for all values produced by this iterator, otherwise false.

20

def foreach(f: (A) => Unit): Unit

Applies a function f to all values produced by this iterator.

21

def hasDefiniteSize: Boolean

Returns true for empty Iterators, false otherwise.

22

def indexOf(elem: B): Int

Returns the index of the first occurrence of the specified object in this iterable object.

23

def indexWhere(p: (A) => Boolean): Int

Returns the index of the first produced value satisfying a predicate, or -1.

24

def isEmpty: Boolean

Returns true if hasNext is false, false otherwise.

25

def isTraversableAgain: Boolean

Tests whether this Iterator can be repeatedly traversed.

26

def length: Int

Returns the number of elements in this iterator. The iterator is at its end after this method returns.

27

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

28

def max: A

Finds the largest element. The iterator is at its end after this method returns.

29

def min: A

Finds the minumum element. The iterator is at its end after this method returns.

30

def mkString: String

Displays all elements of this traversable or iterator in a string.

31

def mkString(sep: String): String

Displays all elements of this traversable or iterator in a string using a separator string.

32

def nonEmpty: Boolean

Tests whether the traversable or iterator is not empty.

33

def padTo(len: Int, elem: A): Iterator[A]

Appends an element value to this iterator until a given target length is reached.

34

def patch(from: Int, patchElems: Iterator[B], replaced: Int): Iterator[B]

Returns this iterator with patched values.

35

def product: A

Multiplies up the elements of this collection.

36

def sameElements(that: Iterator[_]): Boolean

Returns true, if both iterators produce the same elements in the same order, false otherwise.

37

def seq: Iterator[A]

Returns a sequential view of the collection.

38

def size: Int

Returns the number of elements in this traversable or iterator.

39

def slice(from: Int, until: Int): Iterator[A]

Creates an iterator returning an interval of the values produced by this iterator.

40

def sum: A

Returns the sum of all elements of this traversable or iterator with respect to the + operator in num.

41

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

42

def toArray: Array[A]

Returns an array containing all elements of this traversable or iterator.

43

def toBuffer: Buffer[B]

Returns a buffer containing all elements of this traversable or iterator.

44

def toIterable: Iterable[A]

Returns an Iterable containing all elements of this traversable or iterator. This will not terminate for infinite iterators.

45

def toIterator: Iterator[A]

Returns an Iterator containing all elements of this traversable or iterator. This will not terminate for infinite iterators.

46

def toList: List[A]

Returns a list containing all elements of this traversable or iterator.

47

def toMap[T, U]: Map[T, U]

Returns a map containing all elements of this traversable or iterator.

48

def toSeq: Seq[A]

Returns a sequence containing all elements of this traversable or iterator.

49

def toString(): String

Converts this iterator to a string.

50

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


scala_collections.htm

Advertisements