

{"id":14244,"date":"2018-05-02T10:20:48","date_gmt":"2018-05-02T10:20:48","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=14244"},"modified":"2021-12-04T10:15:47","modified_gmt":"2021-12-04T04:45:47","slug":"scala-iterator","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/scala-iterator\/","title":{"rendered":"Scala Iterator: A Cheat Sheet to Iterators in Scala"},"content":{"rendered":"<p>We believe you\u2019ve come here after all other collections. Before proceeding, you should read up on <a href=\"https:\/\/data-flair.training\/blogs\/tuples-in-scala-introduction\/\">Scala Tuples<\/a>, another kind of collection. In this tutorial on Scala Iterator, we will discuss iterators, how to create iterator in Scala and process them, and what methods to call on them.<\/p>\n<p>So, let\u2019s begin Scala Iterator Tutorial.<\/p>\n<h3>An Introduction to Iterators in Scala<\/h3>\n<p>After collections like Lists, Sets, and Maps, we will discuss a way to iterate on them(how we can access their elements one by one).<\/p>\n<p>Two important methods in Scala Iterator are next() and hasNext. hasNext will tell if there is another element to return, while next() will return that element.<\/p>\n<h3>Declaring a Scala Iterator<\/h3>\n<p>Basically, to declare an iterator in Scala over a collection, we pass values to Iterator().<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(7,8,9,2,3)\r\nit: Iterator[Int] = non-empty iterator<\/pre>\n<h3>Accessing values with a Scala Iterator<\/h3>\n<p>We take this iterator:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(2,4,3,7,9)\r\nit: Iterator[Int] = non-empty iterator<\/pre>\n<p>Hence, let\u2019s take a simple while loop to iterate:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; while(it.hasNext){\r\n    | println(it.next())}<\/pre>\n<p>2<br \/>\n4<br \/>\n3<br \/>\n7<br \/>\n9<br \/>\nIf we hadn\u2019t provided the println() to it.next(), it would print nothing. Also, once it reaches the end of the iterator, the iterator is now empty.<\/p>\n<h3>Determining Largest and Smallest Elements<\/h3>\n<p>We can use it.min and it.max to determine the largest and smallest elements in a Scala iterator.<\/p>\n<h4>a. min<\/h4>\n<p>This will return the smallest value in the Scala iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.min\r\nres1: Int = 2<\/pre>\n<h4>b. max<\/h4>\n<p>This Scala Iterator will return the largest value in the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.max\r\njava.lang.UnsupportedOperationException: empty.max\r\n at scala.collection.TraversableOnce.max(TraversableOnce.scala:229)\r\n at scala.collection.TraversableOnce.max$(TraversableOnce.scala:227)\r\n at scala.collection.AbstractIterator.max(Iterator.scala:1432)\r\n ... 28 elided<\/pre>\n<p>Wow, okay, we must declare the iterator again since it\u2019s empty now.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator<\/pre>\n<p>And now:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.max\r\nres3: Int = 9<\/pre>\n<p>So, let\u2019s check if the Scala iterator has exhausted now:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.hasNext\r\nres4: Boolean = false<\/pre>\n<p>Yes. Yes, it has.<\/p>\n<h3>Scala Iterator Length<\/h3>\n<p>Further, we can use either of two methods- size and length.<\/p>\n<h4>a. size<\/h4>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.size\r\nres5: Int = 5<\/pre>\n<h4>b. length<\/h4>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.length\r\nres6: Int = 5<\/pre>\n<h3>Methods to Call on an Iterator in Scala<\/h3>\n<p>Next, here are some common methods we can call on an iterator:<\/p>\n<h4>a. def hasNext: Boolean<\/h4>\n<p>If the Scala iterator has another element to return, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.hasNext\r\nres7: Boolean = true\r\nscala&gt; while(it.hasNext){it.next()}\r\nscala&gt; it.hasNext\r\nres9: Boolean = false<\/pre>\n<h4>b. def next(): A<\/h4>\n<p>Now, this returns the next element from the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.next()\r\nres10: Int = 3\r\nscala&gt; it.next()\r\nres11: Int = 2\r\nscala&gt; it.next()\r\nres12: Int = 4\r\nscala&gt; it.next()\r\nres13: Int = 9\r\nscala&gt; it.next()\r\nres14: Int = 7\r\nscala&gt; it.next()<\/pre>\n<pre class=\"EnlighterJSRAW\">java.util.NoSuchElementException: next on empty iterator\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:38)\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:36)\r\n at scala.collection.IndexedSeqLike$Elements.next(IndexedSeqLike.scala:60)\r\n ... 28 elided<\/pre>\n<h4>c. def ++(that: =&gt; Iterator[A]): Iterator[A]<\/h4>\n<p>This concatenates two Scala iterators.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val a=Iterator(1,2,3).++(Iterator(5,6,7))\r\na: Iterator[Int] = non-empty iterator\r\nscala&gt; while(a.hasNext){println(a.next())}<\/pre>\n<p>1<br \/>\n2<br \/>\n3<br \/>\n5<br \/>\n6<br \/>\n7<\/p>\n<h4>d. def addString(b: StringBuilder): StringBuilder<\/h4>\n<p>This appends the elements of the Scala iterator to a String Builder and returns it.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.addString(new StringBuilder())\r\nres18: StringBuilder = 32497<\/pre>\n<h4>e. def addString(b: StringBuilder, sep: String): StringBuilder<\/h4>\n<p>This lets us include a separator for the above functionality.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.addString(new StringBuilder(),\"*\")\r\nres19: StringBuilder = 3*2*4*9*7<\/pre>\n<h4>f. def buffered: BufferedIterator[A]<\/h4>\n<p>This returns a buffered iterator from the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.buffered\r\nres20: scala.collection.BufferedIterator[Int] = non-empty iterator<\/pre>\n<h4>g. def contains(elem: Any): Boolean<\/h4>\n<p>If the Scala iterator contains element <i>elem<\/i>, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.contains(9)\r\nres21: Boolean = true\r\nscala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.contains(8)\r\nres22: Boolean = false<\/pre>\n<h4>h. def copyToArray(xs: Array[A], start: Int, len: Int): Unit<\/h4>\n<p>This copies the elements of the array, beginning at index <i>start<\/i>, and for length <i>len<\/i>, into an Array.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; var arr=Array(0,0,0,0,0,0,0,0,0,0,0)\r\narr: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\r\nscala&gt; it.copyToArray(arr,2,3)\r\nscala&gt; arr\r\nres28: Array[Int] = Array(0, 0, 3, 2, 4, 0, 0, 0, 0, 0, 0)<\/pre>\n<h4>i. def count(p: (A) =&gt; Boolean): Int<\/h4>\n<p>This counts the number of elements that satisfy a predicate and returns this count.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.count(x=&gt;{x%2!=0})\r\nres29: Int = 3<\/pre>\n<h4>j. def drop(n: Int): Iterator[A]<\/h4>\n<p>This moves the iterator n places ahead. If n is greater than the iterator\u2019s length, this simply exhausts it.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; var it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it=it.drop(2)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.next()\r\nres35: Int = 4\r\nscala&gt; it=it.drop(4)\r\nit: Iterator[Int] = empty iterator\r\nscala&gt; it.next()<\/pre>\n<pre class=\"EnlighterJSRAW\">java.util.NoSuchElementException: next on empty iterator\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:38)\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:36)\r\n at scala.collection.IndexedSeqLike$Elements.next(IndexedSeqLike.scala:60)\r\n ... 28 elided<\/pre>\n<h4>k. def dropWhile(p: (A) =&gt; Boolean): Iterator[A]<\/h4>\n<p>This keeps advancing the iterator as long as the predicate is satisfied.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; var it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it=it.dropWhile(x=&gt;{x&lt;4})\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.next()\r\nres37: Int = 4\r\nscala&gt; it.next()\r\nres38: Int = 9\r\nscala&gt; it.next()\r\nres39: Int = 7<\/pre>\n<h4>l. def duplicate: (Iterator[A], Iterator[A])<\/h4>\n<p>This creates a duplicate of the iterator that will iterate over the same sequence of values.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.duplicate\r\nit1: (Iterator[Int], Iterator[Int]) = (non-empty iterator,non-empty iterator)<\/pre>\n<h4>m. def exists(p: (A) =&gt; Boolean): Boolean<\/h4>\n<p>If the predicate holds true for some values in the iterator, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.exists(x=&gt;{x%3==0})\r\nres41: Boolean = true\r\nscala&gt; it.exists(x=&gt;{x%5==0})\r\nres42: Boolean = false<\/pre>\n<h4>n. def filter(p: (A) =&gt; Boolean): Iterator[A]<\/h4>\n<p>This filters out such elements (see above)<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.filter(x=&gt;{x%3==0})\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; it1.next()\r\nres44: Int = 3\r\nscala&gt; it1.next()\r\nres45: Int = 9\r\nscala&gt; it1.next()<\/pre>\n<pre class=\"EnlighterJSRAW\">java.util.NoSuchElementException: next on empty iterator\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:38)\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:36)\r\n at scala.collection.Iterator$$anon$12.next(Iterator.scala:516)\r\n ... 28 elided<\/pre>\n<h4>o. def filterNot(p: (A) =&gt; Boolean): Iterator[A]<\/h4>\n<p>Parallelly, this will create a new iterator with only those elements that do not satisfy the predicate.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.filterNot(x=&gt;{x%3==0})\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; it1.next()\r\nres47: Int = 2\r\nscala&gt; it1.next()\r\nres48: Int = 4\r\nscala&gt; it1.next()\r\nres49: Int = 7\r\nscala&gt; it1.next()<\/pre>\n<h4>p. def find(p: (A) =&gt; Boolean): Option[A]<\/h4>\n<p>This returns the first value, if any, that satisfies the predicate.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it1=it.find(x=&gt;{x%3==0})\r\nit1: Option[Int] = Some(3)<\/pre>\n<p>This creates an Option.<\/p>\n<h4>q. def forall(p: (A) =&gt; Boolean): Boolean<\/h4>\n<p>If the predicate holds true for all values in the Scala iterator, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.forall(x=&gt;{x%3==0})\r\nres51: Boolean = false<\/pre>\n<h4>r. def hasDefiniteSize: Boolean<\/h4>\n<p>If the iterator is empty, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.hasDefiniteSize\r\nres56: Boolean = true\r\nscala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.hasDefiniteSize\r\nres57: Boolean = false<\/pre>\n<h4>s. def indexOf(elem: B): Int<\/h4>\n<p>This returns the index of the first occurrence of the element <i>elem<\/i> in the Scala iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.indexOf(2)\r\nres58: Int = 1<\/pre>\n<h4>t. def indexWhere(p: (A) =&gt; Boolean): Int<\/h4>\n<p>This returns the index of the first value that satisfies the predicate. If there\u2019s none, it returns -1.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.indexWhere(x=&gt;{x%7==0})\r\nres60: Int = 4\r\nscala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.indexWhere(x=&gt;{x%8==0})\r\nres61: Int = -1<\/pre>\n<h4>u. def isEmpty: Boolean<\/h4>\n<p>If hasNext returns false, then the iterator is empty.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; it.isEmpty\r\nres62: Boolean = true\r\nscala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.next()\r\nres63: Int = 3\r\nscala&gt; it.hasNext\r\nres64: Boolean = true\r\nscala&gt; it.isEmpty\r\nres65: Boolean = false<\/pre>\n<h4>v. def isTraversableAgain: Boolean<\/h4>\n<p>If we can repeatedly traverse the iterator, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.isTraversableAgain\r\nres66: Boolean = false<\/pre>\n<h4>w. def length: Int<\/h4>\n<p>Here, this returns the number of elements in the iterator. Once we\u2019ve called this method, the iterator exhausts.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.length\r\nres69: Int = 5\r\nscala&gt; it\r\nres70: Iterator[Int] = empty iterator<\/pre>\n<h4>x. def map[B](f: (A) =&gt; B): Iterator[B]<\/h4>\n<p>This applies the function to every value in the iterator and then returns a new iterator from this.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.map(x=&gt;{x*x})\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; it1.next()\r\nres72: Int = 9\r\nscala&gt; it1.next()\r\nres73: Int = 4\r\nscala&gt; it1.next()\r\nres74: Int = 16\r\nscala&gt; it1.next()\r\nres75: Int = 81\r\nscala&gt; it1.next()\r\nres76: Int = 49<\/pre>\n<h4>y. def max: A<\/h4>\n<p>This returns the largest element from the Scala iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.max\r\nres77: Int = 9<\/pre>\n<h4>z. def min: A<\/h4>\n<p>This returns the smallest element from the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.min\r\nres78: Int = 2<\/pre>\n<h4>aa. def mkString: String<\/h4>\n<p>This represents all the elements of the iterator as a String.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.mkString\r\nres79: String = 32497<\/pre>\n<h4>ab. def mkString(sep: String): String<\/h4>\n<p>This allows us to declare a separator for the same (see above)<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.mkString(\"*\")\r\nres80: String = 3*2*4*9*7<\/pre>\n<h4>ac. def nonEmpty: Boolean<\/h4>\n<p>If the iterator in Scala is empty, this returns false; otherwise, true.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.nonEmpty\r\nres81: Boolean = true\r\nscala&gt; while(it.hasNext){it.next()}\r\nscala&gt; it.nonEmpty\r\nres83: Boolean = false<\/pre>\n<h4>ad. def product: A<\/h4>\n<p>This multiplies all elements from the iterator and returns the result.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.product\r\nres92: Int = 1512<\/pre>\n<h4>ae. def sameElements(that: Iterator[_]): Boolean<\/h4>\n<p>If both iterators produce the same elements in the same order, this returns true; otherwise, false.<\/p>\n<pre class=\"EnlighterJSRAW\">val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=Iterator(3,4,2,9,7)\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; it.sameElements(it1)\r\nres93: Boolean = false\r\nscala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it2=Iterator(3,2,4,9,7)\r\nit2: Iterator[Int] = non-empty iterator\r\nscala&gt; it.sameElements(it2)\r\nres99: Boolean = true<\/pre>\n<h4>af. def seq: Iterator[A]<\/h4>\n<p>This returns a sequential view of the iterator in Scala.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.seq\r\nres100: Iterator[Int] = non-empty iterator\r\nscala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; for(i&lt;-it.seq){println(i)}<\/pre>\n<p>3<br \/>\n2<br \/>\n4<br \/>\n9<br \/>\n7<\/p>\n<h4>ag. def size: Int<\/h4>\n<p>This returns the size of the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.size\r\nres102: Int = 5<\/pre>\n<h4>ah. def slice(from: Int, until: Int): Iterator[A]<\/h4>\n<p>This creates a new iterator with elements from <i>from<\/i> until <i>until<\/i>.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.slice(1,4)\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; while(it1.hasNext){println(it1.next())}<\/pre>\n<p>2<br \/>\n4<br \/>\n9<\/p>\n<h4>ai. def sum: A<\/h4>\n<p>This returns the sum of all elements in the Scala iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.sum\r\nres1: Int = 25<\/pre>\n<h4>aj. def take(n: Int): Iterator[A]<\/h4>\n<p>This returns the first n values from the iterator, or the entire iterator, whichever is shorter.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.take(3)\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; while(it1.hasNext){println(it1.next())}<\/pre>\n<p>3<br \/>\n2<br \/>\n4<\/p>\n<h4>ak. def toArray: Array[A]<\/h4>\n<p>This returns an Array from the elements of the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.toArray\r\nres4: Array[Int] = Array(3, 2, 4, 9, 7)<\/pre>\n<h4>al. def toBuffer: Buffer[B]<\/h4>\n<p>This returns a Buffer from the iterator\u2019s elements.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.toBuffer\r\nres5: scala.collection.mutable.Buffer[Int] = ArrayBuffer(3, 2, 4, 9, 7)<\/pre>\n<h4>am. def toIterable: Iterable[A]<\/h4>\n<p>This returns a Scala iterable holding all elements of the iterator in Scala. This doesn\u2019t terminate for infinite iterators. Let&#8217;s take a Scala Iterable Example.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.toIterable\r\nres6: Iterable[Int] = Stream(3, ?)\r\nan. def toIterator: Iterator[A]<\/pre>\n<p>Basically, this returns a new iterator from the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; val it1=it.toIterator\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; while(it1.hasNext){println(it1.next())}<\/pre>\n<p>3<br \/>\n2<br \/>\n4<br \/>\n9<br \/>\n7<\/p>\n<h4>an. def toList: List[A]<\/h4>\n<p>This Scala iterator to list returns a List from the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.toList\r\nres9: List[Int] = List(3, 2, 4, 9, 7)\r\nap. def toSeq: Seq[A]<\/pre>\n<p>This returns a Sequence from the iterator.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.toSeq\r\nres11: Seq[Int] = Stream(3, ?)<\/pre>\n<h4>ao. def toString(): String<\/h4>\n<p>This represents the iterator as a String.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Iterator(3,2,4,9,7)\r\nit: Iterator[Int] = non-empty iterator\r\nscala&gt; it.toString\r\nres12: String = non-empty iterator<\/pre>\n<h4>ap. def zip[B](that: Iterator[B]): Iterator[(A, B)<\/h4>\n<p>This returns a new Scala iterator holding pairs of corresponding elements in the iterator. How many elements does this return? Whatever\u2019s minimum of the sizes of both iterators.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it1=Iterator(0,0,0,0,0,0,0,0,0,0)\r\nit1: Iterator[Int] = non-empty iterator\r\nscala&gt; it.zip(it1)\r\nres14: Iterator[(Int, Int)] = non-empty iterator<\/pre>\n<p>So, this was all about Scala Iterators. Hope you like our explanation.<\/p>\n<h3>Conclusion<\/h3>\n<p>Finally, we have seen Scala iterators. Moreover, we also discuss the ways to access collection elements one by one. Furthermore, if you have any query, feel free to ask in the comment section.<\/p>\n<p><a href=\"https:\/\/www.scala-lang.org\/docu\/files\/collections-api\/collections_43.html\">For reference<\/a><span hidden class=\"__iawmlf-post-loop-links\" data-iawmlf-links=\"[{&quot;id&quot;:1959,&quot;href&quot;:&quot;https:\\\/\\\/www.scala-lang.org\\\/docu\\\/files\\\/collections-api\\\/collections_43.html&quot;,&quot;archived_href&quot;:&quot;http:\\\/\\\/web-wp.archive.org\\\/web\\\/20250129205331\\\/https:\\\/\\\/www.scala-lang.org\\\/docu\\\/files\\\/collections-api\\\/collections_43.html&quot;,&quot;redirect_href&quot;:&quot;&quot;,&quot;checks&quot;:[{&quot;date&quot;:&quot;2025-12-10 13:43:28&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-01-07 08:03:58&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-04-01 15:48:17&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-05-08 06:45:28&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-06-17 07:02:23&quot;,&quot;http_code&quot;:206},{&quot;date&quot;:&quot;2026-07-01 19:38:05&quot;,&quot;http_code&quot;:206}],&quot;broken&quot;:false,&quot;last_checked&quot;:{&quot;date&quot;:&quot;2026-07-01 19:38:05&quot;,&quot;http_code&quot;:206},&quot;process&quot;:&quot;done&quot;}]\"><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>We believe you\u2019ve come here after all other collections. Before proceeding, you should read up on Scala Tuples, another kind of collection. In this tutorial on Scala Iterator, we will discuss iterators, how to&#46;&#46;&#46;<\/p>\n","protected":false},"author":6,"featured_media":34755,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[61],"tags":[227,3637,12484],"class_list":["post-14244","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scala","tag-accessing-values-with-a-scala-iterator","tag-declaring-a-scala-iterator","tag-scala-iterator"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Scala Iterator: A Cheat Sheet to Iterators in Scala - DataFlair<\/title>\n<meta name=\"description\" content=\"Scala Iterator Tutorial: Learn Iterators in Scala, declaring an iterator, accessing values with Scala iterator, determining largest and smallest elements\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/scala-iterator\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Scala Iterator: A Cheat Sheet to Iterators in Scala - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Scala Iterator Tutorial: Learn Iterators in Scala, declaring an iterator, accessing values with Scala iterator, determining largest and smallest elements\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/scala-iterator\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-05-02T10:20:48+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-12-04T04:45:47+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/05\/Scala-Collections-Iterators-01.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Scala Iterator: A Cheat Sheet to Iterators in Scala - DataFlair","description":"Scala Iterator Tutorial: Learn Iterators in Scala, declaring an iterator, accessing values with Scala iterator, determining largest and smallest elements","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/scala-iterator\/","og_locale":"en_US","og_type":"article","og_title":"Scala Iterator: A Cheat Sheet to Iterators in Scala - DataFlair","og_description":"Scala Iterator Tutorial: Learn Iterators in Scala, declaring an iterator, accessing values with Scala iterator, determining largest and smallest elements","og_url":"https:\/\/data-flair.training\/blogs\/scala-iterator\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-05-02T10:20:48+00:00","article_modified_time":"2021-12-04T04:45:47+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/05\/Scala-Collections-Iterators-01.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/2c58ecb4f73a39f0ef993f1ddfcd7b89"},"headline":"Scala Iterator: A Cheat Sheet to Iterators in Scala","datePublished":"2018-05-02T10:20:48+00:00","dateModified":"2021-12-04T04:45:47+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/"},"wordCount":1186,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/05\/Scala-Collections-Iterators-01.jpg","keywords":["Accessing Values with a Scala Iterator","Declaring a Scala Iterator","Scala Iterator"],"articleSection":["Scala Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/scala-iterator\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/","url":"https:\/\/data-flair.training\/blogs\/scala-iterator\/","name":"Scala Iterator: A Cheat Sheet to Iterators in Scala - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/05\/Scala-Collections-Iterators-01.jpg","datePublished":"2018-05-02T10:20:48+00:00","dateModified":"2021-12-04T04:45:47+00:00","description":"Scala Iterator Tutorial: Learn Iterators in Scala, declaring an iterator, accessing values with Scala iterator, determining largest and smallest elements","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/scala-iterator\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/05\/Scala-Collections-Iterators-01.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/05\/Scala-Collections-Iterators-01.jpg","width":1200,"height":628,"caption":"Scala iterator"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/scala-iterator\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Scala Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/scala\/"},{"@type":"ListItem","position":3,"name":"Scala Iterator: A Cheat Sheet to Iterators in Scala"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/2c58ecb4f73a39f0ef993f1ddfcd7b89","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"The DataFlair Team provides industry-driven content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our expert educators focus on delivering value-packed, easy-to-follow resources for tech enthusiasts and professionals.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam2\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/14244","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=14244"}],"version-history":[{"count":7,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/14244\/revisions"}],"predecessor-version":[{"id":104859,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/14244\/revisions\/104859"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/34755"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=14244"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=14244"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=14244"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}