Scala Map find() 方法与示例
find()方法用于查找满足给定谓词的映射的第一个元素。
Method Definition: def find(p: ((A, B)) => Boolean): Option[(A, B)]
Return Type: It returns the first element of the map which satisfies the given predicate.
示例 #1:
// Scala program of find()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating map
val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs")
// Applying find method
val result = m1.find(_._2 == "for")
// Displays output
println(result)
}
}
输出:
Some((1, for))
因此,这里第二对是满足给定谓词的第一对,因此返回第二对。
示例 #2:
// Scala program of find()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating map
val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs", 6 -> "geeks")
// Applying find method
val result = m1.find(_._2 == "geeks")
// Displays output
println(result)
}
}
输出:
Some((3, geeks))