Scala Map filter() 方法与示例
filter()方法用于选择满足指定谓词的映射的所有元素。
Method Definition: def filter(p: ((A, B))=> Boolean): Map[A, B]
Return Type: It returns a new map consisting all the elements of the map which satisfies the given predicate.
示例 #1:
// Scala program of filter()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating map
val m1 = Map("geeks" -> 5, "for" -> 3)
// Applying filter method
val result = m1.filter(x => x._1 == "geeks" && x._2 == 5)
// Displays output
println(result)
}
}
输出:
Map(geeks -> 5)
示例 #2:
// Scala program of filter()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating map
val m1 = Map("geeks" -> 5, "for" -> 3)
// Applying filter method
val result = m1.filter(x => x._1 == "for" && x._2 == 5)
// Displays output
println(result)
}
}
输出:
Map()
此处,由于没有元素满足所述谓词,因此返回一个空映射。