📜  Scala Map filter() 方法与示例

📅  最后修改于: 2022-05-13 01:54:53.901000             🧑  作者: Mango

Scala Map filter() 方法与示例

filter()方法用于选择满足指定谓词的映射的所有元素。

示例 #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()

此处,由于没有元素满足所述谓词,因此返回一个空映射。