Scala TreeSet find()方法及示例
在Scala TreeSet类中, find() 方法被用来返回TreeSet中满足给定谓词的元素。
方法定义: def find(p: (A) => Boolean):Option[A]
返回类型。如果存在的话,它返回满足给定谓词的第一个元素,否则就返回None。
例子 #1:
// Scala program of find()
// method
// Import TreeSet
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating TreeSet
val t1 = TreeSet(2, 4, 6, 7, 8, 9)
// Print the TreeSet
println(t1)
// Applying find() method
val result = t1.find(x => {x % 7 == 0})
// Displays output
println("Element divisible by 7: " + result)
}
}
输出。
TreeSet(2, 4, 6, 7, 8, 9)
Element divisible by 7: Some(7)
例子#2。
// Scala program of find()
// method
// Import TreeSet
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating TreeSet
val t1 = TreeSet(2, 4, 6, 7, 8, 9)
// Print the TreeSet
println(t1)
// Applying find() method
val result = t1.find(x => {x % 10 == 0})
// Displays output
println("Element divisible by 10: " + result)
}
}
输出。
TreeSet(2, 4, 6, 7, 8, 9)
Element divisible by 10: None