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.

  • 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 :



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

3

Here, the value 9 in the indexOf method is present in the third position of the iterator so, it returns three.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.