The indexOf() method belongs to the concrete value members of the class Abstract Iterator. It is helpful in searching the values and then indicating their positions in the stated iterator.
-
Method Definition:
def indexOf(elem: B): Int
Where, elem is the element to be searched.
-
Return Type:
It returns the index of the first occurrence of the element elem in the stated Scala iterator.
Example :
// Scala program of indexOf() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Declaring an iterator
val iter = Iterator( 2 , 3 , 4 , 9 , 6 )
// Applying indexOf method
val result = iter.indexOf( 9 )
// Displays output
println(result)
}
} |
3
Here, the value 9 in the indexOf method is present in the third position of the iterator so, it returns three.
Example :
// Scala program of indexOf() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Declaring an iterator
val iter = Iterator( 2 , 3 , 4 , 9 , 6 )
// Applying indexOf method
val result = iter.indexOf( 7 )
// Displays output
println(result)
}
} |
-1
Here, the value stated in the method indexOf is not present in the iterator so, it returns -1.
Note: If the value given in the indexOf method is not present in the stated iterator then this method will return -1.