Scala Iterator indexWhere() method with example

The indexWhere() method belongs to the concrete value members of iterator class in Scala. This method will find the position of the first value of the iterator that satisfies the stated predicate.

  • Method Definition:

    def indexWhere(p: (A) => Boolean): Int
    

    Where, p is the predicate stated.

  • Return Type:
    It returns the index of the first value of the iterator that satisfies the stated predicate and if none of the values in the iterator satisfies the stated predicate then this method returns -1.

Example :



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of indexWhere()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Declaring an iterator
        val iter = Iterator(3, 1, 4, 9, 6)
          
        // Applying indexWhere method
        // with a predicate
        val result = iter.indexWhere(x=>{x % 2==0})
          
        // Displays output
        println(result)
  
    }

chevron_right


Output:

2

Here, the given predicate is satisfied by the value of the iterator at the third position i.e, index 2 so, two is returned.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of indexWhere()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Declaring an iterator
        val iter = Iterator(3, 1, 7, 9, 15)
          
        // Applying indexWhere method
        // with a predicate
        val result = iter.indexWhere(x=>{x % 2==0})
          
        // Displays output
        println(result)
  
    }
}     

chevron_right


Output:

-1

Here, the stated predicate is not satisfied by any of the values of the iterator so, -1 is returned in such cases.



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.