带有示例的 Scala 迭代器 find() 方法
find()方法属于AbstractIterator类的具体值成员。它在类IterableOnceOps中定义。它找到满足给定谓词的所述集合的第一个元素。对于无限大小的集合,它不会终止。
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.
示例 #1:
// 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)
}
}
输出:
Some(2)
示例 #2:
// 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)
}
}
输出:
None