Using Scala Iterator: Basic Operations, Examples, and Common Methods
This article explains Scala's Iterator as a traversal tool rather than a collection, covering its core methods next and hasNext, demonstrating iteration with while loops, showing how to find min/max elements, obtain size, and providing a comprehensive table of common Iterator methods with code examples.
Scala Iterator is not a collection; it is a way to access elements of a collection.
The two basic operations of an iterator it are next and hasNext .
Calling it.next() returns the next element and updates the iterator's state.
Calling it.hasNext() checks whether there are more elements in the collection.
The simplest way to let the iterator return all elements one by one is to use a while loop:
object Test {
def main(args: Array[String]) {
val it = Iterator("Baidu", "Google", "Runoob", "Taobao")
while (it.hasNext){
println(it.next())
}
}
}Running the above code produces the output:
$ scalac Test.scala
$ scala Test
Baidu
Google
Runoob
TaobaoFind Maximum and Minimum Elements
You can use it.min and it.max to find the smallest and largest elements in an iterator.
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 element: " + ita.max )
println("Minimum element: " + itb.min )
}
}Running this code outputs:
$ scalac Test.scala
$ scala Test
Maximum element: 90
Minimum element: 2Get Iterator Length
You can use it.size or it.length to see how many elements the iterator contains.
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("ita.size value: " + ita.size )
println("itb.length value: " + itb.length )
}
}Running this code produces:
$ scalac Test.scala
$ scala Test
ita.size value: 6
itb.length value: 6Scala Iterator Common Methods
The table below lists frequently used methods of Scala's Iterator.
No.
Method and Description
1
def hasNext: Boolean
– Returns true if there are more elements.
2
def next(): A
– Returns the next element and advances 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
– Appends a string to the given StringBuilder.
6
def addString(b: StringBuilder, sep: String): StringBuilder
– Appends a string with a separator.
7
def buffered: BufferedIterator[A]
– Converts the iterator to a BufferedIterator.
8
def contains(elem: Any): Boolean
– Checks if the iterator contains the specified element.
9
def copyToArray(xs: Array[A], start: Int, len: Int): Unit
– Copies selected values to an array.
10
def count(p: (A) => Boolean): Int
– Counts elements satisfying the predicate.
11
def drop(n: Int): Iterator[A]
– Returns a new iterator without the first n elements.
12
def dropWhile(p: (A) => Boolean): Iterator[A]
– Drops elements while the predicate holds.
13
def duplicate: (Iterator[A], Iterator[A])
– Produces two iterators that can each traverse all elements.
14
def exists(p: (A) => Boolean): Boolean
– Returns true if any element satisfies the predicate.
15
def filter(p: (A) => Boolean): Iterator[A]
– Returns a new iterator of elements that satisfy the predicate.
16
def filterNot(p: (A) => Boolean): Iterator[A]
– Returns a new iterator of elements that do not satisfy the predicate.
17
def find(p: (A) => Boolean): Option[A]
– Returns the first element satisfying the predicate or None.
18
def flatMap[B](f: (A) => GenTraversableOnce[B]): Iterator[B]
– Applies a function to each element and flattens the results.
19
def forall(p: (A) => Boolean): Boolean
– Returns true if all elements satisfy the predicate.
20
def foreach(f: (A) => Unit): Unit
– Executes a function for each element.
21
def hasDefiniteSize: Boolean
– Returns true if the iterator has a finite size.
22
def indexOf(elem: B): Int
– Returns the index of the first occurrence of the element.
23
def indexWhere(p: (A) => Boolean): Int
– Returns the index of the first element satisfying the predicate.
24
def isEmpty: Boolean
– Checks if the iterator is empty (opposite of hasNext).
25
def isTraversableAgain: Boolean
– Tests whether the iterator can be traversed repeatedly.
26
def length: Int
– Returns the number of elements.
27
def map[B](f: (A) => B): Iterator[B]
– Transforms each element with a function.
28
def max: A
– Returns the maximum element.
29
def min: A
– Returns the minimum element.
30
def mkString: String
– Concatenates all elements into a string.
31
def mkString(sep: String): String
– Concatenates elements with a separator.
32
def nonEmpty: Boolean
– Checks if the iterator contains any elements.
33
def padTo(len: Int, elem: A): Iterator[A]
– Extends the iterator to a given length by appending a value.
34
def patch(from: Int, patchElems: Iterator[B], replaced: Int): Iterator[B]
– Replaces a slice of elements with another iterator.
35
def product: A
– Returns the product of numeric elements.
36
def sameElements(that: Iterator[_]): Boolean
– Checks if two iterators produce the same elements in order.
37
def seq: Iterator[A]
– Returns a sequential view of the collection.
38
def size: Int
– Returns the number of elements.
39
def slice(from: Int, until: Int): Iterator[A]
– Returns a sub‑iterator from the start index up to, but not including, the end index.
40
def sum: A
– Returns the sum of numeric elements.
41
def take(n: Int): Iterator[A]
– Returns an iterator of the first n elements.
42
def toArray: Array[A]
– Copies all elements into an array.
43
def toBuffer: Buffer[B]
– Copies all elements into a Buffer.
44
def toIterable: Iterable[A]
– Returns an Iterable containing all elements (may not terminate for infinite iterators).
45
def toIterator: Iterator[A]
– Returns a new Iterator containing all elements.
46
def toList: List[A]
– Returns a List of all elements.
47
def toMap[T, U]: Map[T, U]
– Converts key‑value pairs into a Map.
48
def toSeq: Seq[A]
– Returns a Seq of all elements.
49
def toString(): String
– Converts the iterator to a string representation.
50
def zip[B](that: Iterator[B]): Iterator[(A, B)]
– Zips two iterators into a sequence of pairs.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
