Open In App

Scala Iterator indexOf() method with example

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.

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)
  
    }

Output:
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)
  
    }

Output:

-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.


Article Tags :