Updated March 30, 2023
Definition of Scala Iterator
Iterator is used to iterate the elements with the use of this we can able to access the elements of collection individually and perform operations as well. Iterator is very different from a collection or we can say it is not a collection rather we use it to succeed the elements which are present inside the collection. It has two methods that make us unable to access the next elements from collections. Also, iterate does not load the whole collection at once so it is used with a large number of big data in terms of memory utilization. It provide us hasNext() and next() method to work with collection elements.
Syntax:
The basic syntax to define the iterate in scala is as follows;
valiterate_name = Iterator(value1, value2, value3, so on ....)
Example:
val iterate1 = Iterator(100, 200, 300, 400, 500, 600)
In this way, we can define an iterate in scala. We are using the var keyword to define out iterate variable followed by iterator object containing the values separated by commas. In detail, we will discuss them in the next section. Syntax to use its method for access elements in scala is as follows;
- To access next element:while(iterate1.hasNext)
- To print the element we have next:println(iterate1.next)
How do Iterators Work in Scala?
Iterator we can say a data structure that allows us to iterate collections. Iterator is used to iterate the collection elements one by one in scala, it works in the same way as java. It contains two methods hasNext and next to the operator the collection elements. Iterator is mutable in nature which means we can change the value of the element once assign.
- hasNext: This method we used to access the next element of the collection. Mostly we use this method inside the while loop or any other loops available. This method checks whether the next element is present in the collection or not. This method returns a Boolean true or false based on the element found.
- next: This method returns the next element from the collection. If the next element is not present and we try to call the next method it will throw an exception saying; NoSuchElementExaception.
It contains both abstract and concrete value members. Now we will take about its extended, super types and known subclasses for iterator which is as follows;
1. Extended classes available in scala;
- IterableOnce[A]
- IterableOnceOps[A, Iterator, Iterator[A]]
2. Supertype available in scala;
- IterableOnceOps[A, Iterator, Iterator[A]]
- AnuRef
- Any
- IterableOnce[A]
3. Known subclasses available in scala;
- AbstractIterator
- BufferedIterator
- GroupedIterator
- BufferedSource
- Source
- LineIterotor
- MatchIterator
Let’s take look at one simple program for beginners to understand its works;
object Main extends App{
// Your code here!
// creating array and assigning values to iterate
val ite1 = Array(100 , 200, 300, 400, 500, 600)
//calling iterator
val result = ite1.iterator
//using methods here to access elements!!
while (result.hasNext) {
println("value is :::")
println(result.next)
}
}
In the above example, we are creating one array and initializing its value. This array will be used later to iterate. After that, we are calling the iterator method on the array object to iterate the elements of the array. Inside while loop we are calling hasNext() methods to check element is present or not if yes it will go inside the loop otherwise no. If the hasNext() method returns true then we are using the next() method to access the current element and print it.
Iterators Method in Scala with Example
Following are the examples are given below:
Example #1
This example will show the simple working of iterator using method hasNext and next.
Code:
object Main extends App{
// Your code here!
// creating array to iterate
val ite1 = Array(100 , 200, 300, 400, 500, 600)
//calling iterator
val result = ite1.iterator
//using methods here to access elements!!
while (result.hasNext) {
println("value is :::")
println(result.next)
}
}
Output:
Example #2
In this example, we are iterating the List collection using the iterator method and doing modifications on the elements.
Code:
object Main extends App{
// Your code here!
// creating array to iterate
val ite1 = List(100 , 200, 300, 400, 500, 600)
//calling iterator
val result = ite1.iterator
//using methods here to access elements!!
while (result.hasNext) {
println("value is :::")
varnum = result.next + 100
println("value after modification is :::")
println(num)
}
}
Output:
Example #3
In this example, we are converting a list of strings to uppercase using the iterator in scala.
Code:
object Main extends App{
// Your code here!
// creating array to iterate
val ite1 = List("hello", "bye", "amit", "world", "hihihih", "stirniii")
//calling iterator
val result = ite1.iterator
//using methods here to access elements!!
while (result.hasNext) {
println("value is :::")
varnum = result.next.toUpperCase
println("converting value to uppercase :: :::")
println(num)
} }
Output:
Example #4
In this example, we are using for loop to access iterate objects in scala.
Code:
object Main extends App{
// Your code here!
// creating array to iterate
val ite1 = List("hello", "bye", "amit", "world", "hihihih", "stirniii")
//calling iterator
val result = ite1.iterator
//using methods here to access elements!!
//using for loop
for(obj<- result) {
println("value is :::")
println(obj)
} }
Output:
Example #5
In this example, we are using the max and min method to find the maximum and minimum elements present in the iterator.
Code:
object Main extends App{
// Your code here!
// defining iterator
val itr1 = Iterator(500, 1500, 200, 900, 560, 3457, 7900)
val itr2 = Iterator(500, 1500, 200, 900, 560, 3457, 7900)
//using max min
var max = itr1.max
var min = itr2.min
//printing result ::
println("maximum value from list is :::")
println(max)
println("minimum value from list is :::")
println(min)
}
Output:
Conclusion – Scala Iterator
Iterator is used to iterate the elements of the collection. They are very efficient when it comes to memory utilization because they handle large data because they do not load all the data at once like collection in scala. Also, it throws an exception when we try to access an element which does not exist.
Recommended Articles
This is a guide to Scala Iterator. Here we also discuss the introduction and how do iterators works in scala? along with different examples and its code implementation. You may also have a look at the following articles to learn more –