English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Iterator (Iterators)

Scala Collections

Scala Iterator (iterator) is not a collection; it is a method used to access collections.

The two basic operations of the iterator it are next and hasNext.

Call it.next() It will return the next element of the iterator and update the iterator's state.

Call it.hasNext() used to check if there are still elements in the collection.

The simplest way to let the iterator it return all elements one by one is to use a while loop:

object Test {
   def main(args: Array[String]) {
      val it = Iterator("Baidu", "Google", "w3"codebox", "Taobao")
      
      while (it.hasNext){
         println(it.next())
      }
   }
}

After executing the above code, the output is as follows:

$ scalac Test.scala 
$ scala Test
Baidu
Google
w3codebox
Taobao

find the maximum and minimum elements

You can use it.min and it.max The method finds the maximum and minimum elements from the iterator, as shown in the following example:

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("The maximum element is: ") + ita.max )
      println("The minimum element is: " + itb.min )
   }
}

After executing the above code, the output is as follows:

$ scalac Test.scala 
$ scala Test
The maximum element is:90
The minimum element is:2

to get the length of the iterator

You can use it.size or it.length Methods to view the number of elements in the iterator. The following is an example:

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("The value of ita.size: " + ita.size )
      println("The value of itb.length: " + itb.length )
   }
}

After executing the above code, the output is as follows:

$ scalac Test.scala 
$ scala Test
The value of ita.size: 6
The value of itb.length: 6

Commonly used methods of Scala Iterator

The following table lists the commonly used methods of Scala Iterator:

Serial numberMethods and descriptions
1

def hasNext: Boolean

Return true if there are more elements to return.

2

def next(): A

Return the next element of the iterator and update the iterator's state

3

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

Merge two iterators

4

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

Merge two iterators

5

def addString(b: StringBuilder): StringBuilder

Add a string to StringBuilder b

6

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

Add a string to StringBuilder b and specify the separator

7

def buffered: BufferedIterator[A]

Convert all iterators to BufferedIterator

8

def contains(elem: Any): Boolean

Check if the iterator contains the specified element

9

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

Pass the selected values from the iterator to the array

10

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

Return the total number of elements in the iterator that meet the condition p.

11

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

Return a new collection with the first n elements discarded

12

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

Discard elements from left to right until the condition p does not hold

13

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

Generate two iterators that can return all elements of the iterator separately.

14

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

Return a boolean value indicating whether there is an element in the iterator that meets the condition p.

15

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

Return a new iterator pointing to all elements of the iterator that meet the condition p.

16

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

Return an iterator pointing to the elements of the iterator that do not meet the condition p.

17

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

Return the first element that meets the condition p or None. Note: if an element that meets the conditions is found, the iterator will be placed after the element; if not found, it will be placed at the end.

18

def flatMap[B](f: (A) => GenTraversableOnce[B]): Iterator[B]

Apply the function f to each element in the sequence of the iterator and return an iterator pointing to the result sequence.

19

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

Return a boolean value indicating whether all elements pointed to by it meet the condition p.

20

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

Execute the specified program f on each element returned by the iterator

21

def hasDefiniteSize: Boolean

Return true if the number of elements in the iterator is finite (default is equivalent to isEmpty)

22

def indexOf(elem: B): Int

Return the first element of the iterator whose index equals x. Note: the iterator will skip this element.

23

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

Return the elements of the iterator whose index meets the condition p. Note: the iterator will skip this element.

24

def isEmpty: Boolean

Checks if 'it' is empty, returns true if it is empty, otherwise returns false (opposite of hasNext)

25

def isTraversableAgain: Boolean

Tests whether this Iterator can be traversed repeatedly.

26

def length: Int

Returns the number of elements in the iterator

27

def map[B](f: (A) => B): Iterator[B]

Applies function 'f' to each element in 'it' and generates a new iterator with the results

28

def max: A

Returns the largest element among the elements pointed to by the iterator

29

def min: A

Returns the smallest element among the elements pointed to by the iterator

30

def mkString: String

Converts all elements of the iterator to a string

31

def mkString(sep: String): String

Converts all elements of the iterator to a string and specifies a delimiter

32

def nonEmpty: Boolean

Checks if the container contains the element (equivalent to hasNext)

33

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

First returns all elements of the iterator, then appends the copy of 'elem' until the length reaches 'len'.

34

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

Returns a new iterator where the 'replaced' elements starting from the 'from' element are replaced by the elements pointed to by the iterator

35

def product: A

Returns the product of the numeric elements pointed to by the iterator

36

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

Determines whether the iterator and the specified iterator parameter return elements in the same order

37

def seq: Iterator[A]

Returns a series view of the collection

38

def size: Int

Returns the number of elements in the iterator

39

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

Returns a new iterator pointing to a segment of the sequence pointed to by the iterator, starting from the element at index 'from' and ending at the element at index 'until'.

40

def sum: A

Returns the sum of the numeric elements pointed to by the iterator

41

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

Returns a new iterator with the first n elements.

42

def toArray: Array[A]

Collects all elements pointed to by the iterator into an array and returns.

43

def toBuffer: Buffer[B]

Copies all elements pointed to by the iterator into the buffer Buffer.

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]

Collects all elements of the iterator into an Iterator container and returns.

46

def toList: List[A]

Collects all elements of the iterator into a list and returns

47

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

Defers all key-value pairs of the iterator into a Map and returns.

48

def toSeq: Seq[A]

Defers all elements of the iterator into a Seq container and returns.

49

def toString(): String

Converts the iterator to a string

50

def zip[B](that: Iterator[B]): Iterator[(A, B)]

Returns a new iterator pointing to a sequence of pairs, where each pair is formed by corresponding elements of the iterator and the specified iterator that.

More methods can be referred to API Documentation

Scala Collections