Scala Map filterKeys()方法及示例
filterKeys()方法是用来找到所有键值满足给定谓词的配对。
方法定义:def filterKeys(p: (A) => Boolean):Map[A, B]
返回类型。它返回Map中所有的 “键-值 “对,其中的键满足给定的谓词。
例子 #1:
// Scala program of filterKeys()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating map
val m1 = Map(5 -> "geeks", 4 -> "for", 2 -> "cs")
// Applying filterKeys method
val result = m1.filterKeys(_ > 2)
// Displays output
println(result)
}
}
输出。
Map(5 -> geeks, 4 -> for)
这里,只有两个键值对被返回,因为根据所述谓词,它们的键值大于2。
例子#2。
// Scala program of filterKeys()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating map
val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs")
// Applying filterKeys method
val result = m1.filterKeys(_ > 3)
// Displays output
println(result)
}
}
输出。
Map()
在这里,由于没有一个键满足所述的谓词,所以没有一对被返回。
极客教程