Skip to content
Related Articles

Related Articles

Scala Iterator indexWhere() method with example
  • Last Updated : 28 May, 2019

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 :




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




// 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)
  
    }
}     
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
Recommended Articles
Page :