Scala Iterator

Scala 集合Scala Collections

Scala Iterator is not a collection; it is a method for accessing collections.

The two basic operations of iterator it are:nextandhasNext。

Callit.next()will return the next element of the iterator and update the state of the iterator.

Callit.hasNext()is used to check whether there are more elements in the collection.

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

Example

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

Executing the above code produces the following output:

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

Find Max and Min Elements

You can useit.minandit.maxmethods to find the maximum and minimum elements from the iterator, as shown in the following example:

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

   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
最大元素是:90
最小元素是:2

Get the Length of an Iterator

You can useit.sizeorit.lengthmethods to view the number of elements in the iterator. Examples are as follows:

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 )

   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
ita.size 的值: 6
itb.length 的值: 6

Common Methods of Scala Iterator

The following table lists the common methods of Scala Iterator:

No. Method and Description
1

def hasNext: Boolean

Returns true if there are elements that can be returned.

2

def next(): A

Returns the next element of the iterator and updates the state of the iterator.

3

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

Concatenates two iterators

4

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

Concatenates two iterators

5

def addString(b: StringBuilder): StringBuilder

Adds a string to StringBuilder b

6

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

Adds a string to StringBuilder b, and specifies a separator

7

def buffered: BufferedIterator[A]

Converts the iterator to a BufferedIterator

8

def contains(elem: Any): Boolean

Checks whether the iterator contains the specified element

9

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

Copies selected values from the iterator to an array

10

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

Returns the total number of elements in the iterator that satisfy condition p.

11

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

Returns a new collection that discards the first n elements

12

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

Drops elements from left to right until condition p is false

13

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

Generates two iterators that can each return all elements of the iterator.

14

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

Returns a Boolean value indicating whether there exists an element satisfying p among the iterator elements.

15

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

Returns a new iterator pointing to all elements of the iterator that satisfy condition p.

16

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

Returns an iterator pointing to elements of the iterator that do not satisfy condition p.

17

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

Returns the first element that satisfies p, or None. Note: If an element satisfying the condition is found, the iterator is positioned after that element; if not found, it is positioned at the end.

18

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

Applies function f to each element in the iterator's sequence, and returns an iterator pointing to the resulting sequence.

19

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

Returns a Boolean value indicating whether all elements referred to by it satisfy p.

20

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

Executes the specified procedure f on each element returned by the iterator.

21

def hasDefiniteSize: Boolean

Returns true if the iterator has a finite number of elements (by default equivalent to isEmpty)

22

def indexOf(elem: B): Int

Returns the first element in the iterator whose index equals x. Note: The iterator will skip this element.

23

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

Returns the element in the iterator whose index satisfies condition p. Note: The iterator will skip this element.

24

def isEmpty: Boolean

Checks whether it is empty; returns true if empty, otherwise returns false (opposite of hasNext).

25

def isTraversableAgain: Boolean

Tests whether this Iterator can be repeatedly traversed.

26

def length: Int

Returns the number of elements in the iterator.

27

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

Generates a new iterator from the results of passing each element in it to function f.

28

def max: A

Returns the largest element among the iterator elements.

29

def min: A

Returns the smallest element among the iterator elements.

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

32

def nonEmpty: Boolean

Checks whether the container contains elements (equivalent to hasNext).

33

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

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

34

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

Returns a new iterator, in which the replaced elements starting from the from-th element are replaced by the elements pointed to by the iterator.

35

def product: A

Returns the product of the numeric elements to which the iterator refers.

36

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

Determines whether the iterator and the specified iterator parameter return the same elements in sequence.

37

def seq: Iterator[A]

Returns the sequence 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 slice of the sequence pointed to by the iterator, starting from the from-th element and ending at the until-th element.

40

def sum: A

Returns the sum of the numeric elements to which the iterator refers.

41

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

Returns a new iterator of the first n elements.

42

def toArray: Array[A]

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

43

def toBuffer: Buffer[B]

Copies all elements pointed to by the iterator to 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 it.

46

def toList: List[A]

Collects all elements of the iterator into a list and returns it.

47

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

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

48

def toSeq: Seq[A]

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

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 two-element tuples formed by pairing elements of the iterator with elements of the specified iterator that one-to-one.

For more methods, please refer tothe API documentation

Scala 集合Scala Collections

Other Extensions