
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Iterators
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 follow the following example program.
Example
object Demo { def main(args: Array[String]) { val it = Iterator("a", "number", "of", "words") while (it.hasNext){ println(it.next()) } } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
a number of words
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. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program.
Example
object Demo { 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 ) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Maximum valued element 90 Minimum valued element 2
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. Here, we used ita and itb to perform two different operations because iterator can be traversed only once. Following is the example program.
Example
object Demo { 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 ) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Value of ita.size : 6 Value of itb.length : 6
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.
Sr.No | 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 minimum 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. The number of elements returned by the new iterator is same as the minimum number of elements returned by the iterator (A or B). |
Duplicate an Iterator
You can duplicate an iterator using the duplicate method. This will create two new iterators from the original iterator. So you can traverse the same elements multiple times.
Example
Consider following example for duplicate an iterator -
object Demo { def main(args: Array[String]) = { val it = Iterator(1, 2, 3, 4, 5) val (it1, it2) = it.duplicate println("First iterator elements:") it1.foreach(println) println("Second iterator elements:") it2.foreach(println) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
First iterator elements: 1 2 3 4 5 Second iterator elements: 1 2 3 4 5
Convert Iterator to List
You can convert an iterator to a list using the toList method. It is used to store the elements of an iterator in a collection that can be traversed multiple times.
Example
Consider following example to convert iterator to a list -
object Demo { def main(args: Array[String]) = { val it = Iterator(6, 7, 8, 9, 10) val list = it.toList println("List: " + list) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
List: List(6, 7, 8, 9, 10)
Using Map with Iterators
You can apply a function to each element of an iterator using the map method. This will create a new iterator where each element is the result of applying the function to the corresponding element of the original iterator.
Example
Consider following example for using map with iterators -
object Demo { def main(args: Array[String]) = { val it = Iterator(1, 2, 3, 4) val mappedIt = it.map(_ * 2) println("Mapped iterator elements:") mappedIt.foreach(println) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Mapped iterator elements: 2 4 6 8
Filtering Elements of an Iterator
You can filter elements of an iterator using the filter method. This creates a new iterator that only contains the elements which satisfy a given predicate.
Example
Consider following example for filtering elements of an iterator -
object Demo { def main(args: Array[String]) = { val it = Iterator(1, 2, 3, 4, 5, 6) val filteredIt = it.filter(_ % 2 == 0) println("Filtered iterator elements (even numbers):") filteredIt.foreach(println) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Filtered iterator elements (even numbers): 2 4 6
Reducing Elements of an Iterator
You can reduce the elements of an iterator to a single value using the reduce method. This is used for operations, like summing all elements and finding the product of all elements.
Example
Consider following example for reducing elements of an iterator -
object Demo { def main(args: Array[String]) = { val it = Iterator(1, 2, 3, 4) val sum = it.reduce(_ + _) println("Sum of elements: " + sum) } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Sum of elements: 10
Scala Iterators Summary
- Iterators in Scala are used to access elements of a collection one by one.
- Basic operations on iterators include next and hasNext.
- Iterators can be traversed using a while loop.
- Methods like min, max, size, and length provide more functionalities.
- You can perform various operations on iterators, like duplicating, converting to list, mapping, filtering, and reducing elements.