Scala Iterator find() method with example

The find() method belong to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It finds the first element of the stated collection which satisfies the given predicate. It would not terminate for the infinite sized collections.

Method Definition : def find(p: (A) => Boolean): Option[A]

Return Type :It returns an Option value containing the first element of the stated collection that satisfies the used predicate else returns None if none exists.



Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of find()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an Iterator 
        val iter = Iterator(2, 4, 5, 1, 13)
          
        // Applying find method
        val result= iter.find(x => {x % 2 == 0})
          
        // Displays output
        println(result)
  
    }
}

chevron_right


Output:

Some(2)

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of find()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an Iterator 
        val iter = Iterator(3, 6, 15, 12, 21)
          
        // Applying find method
        val result= iter.find(x => {x % 3 != 0})
          
        // Displays output
        println(result)
      
    }
}

chevron_right


Output:

None


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.